Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ll;
- import java.util.*;
- import java.util.concurrent.Semaphore;
- class Sema {
- public static Semaphore s;
- }
- class Tred extends Thread {
- private int id;
- private BlockingQueue q;
- public Tred(int id, BlockingQueue q) {
- this.id = id;
- this.q = q;
- }
- public void run() {
- try {
- q.enqueue(5);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- q.dequeue();
- }
- }
- class BlockingQueue<T> {
- T[] contents;
- int capacity;
- static int poz = 0;
- public BlockingQueue(int capacity) {
- contents = (T[]) new Object[capacity];
- this.capacity = capacity;
- }
- public void enqueue(T item) throws InterruptedException {
- Sema.s.acquire();
- contents[poz] = item;
- poz++;
- }
- public void dequeue() {
- if (Sema.s.availablePermits() != capacity) {
- poz--;
- Sema.s.release();
- }
- }
- }
- public class Main {
- public static void main(String[] args) {
- ArrayList<Tred> tr = new ArrayList<>();
- Scanner s = new Scanner(System.in);
- int n = s.nextInt();
- BlockingQueue<Integer> q = new BlockingQueue<>(n);
- Sema.s = new Semaphore(n);
- n = s.nextInt();
- for (int i = 0; i < n; i++) {
- Tred a = new Tred(i, q);
- tr.add(a);
- }
- for (Tred r : tr) {
- r.start();
- }
- for (int i = 0; i < q.contents.length; i++) {
- System.out.println();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement