Advertisement
Guest User

Untitled

a guest
Mar 31st, 2020
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. package ll;
  2.  
  3. import java.util.*;
  4. import java.util.concurrent.Semaphore;
  5.  
  6. class Sema {
  7. public static Semaphore s;
  8.  
  9. }
  10.  
  11. class Tred extends Thread {
  12. private int id;
  13. private BlockingQueue q;
  14.  
  15. public Tred(int id, BlockingQueue q) {
  16. this.id = id;
  17. this.q = q;
  18. }
  19.  
  20. public void run() {
  21. try {
  22. q.enqueue(5);
  23. } catch (InterruptedException e) {
  24. // TODO Auto-generated catch block
  25. e.printStackTrace();
  26. }
  27. q.dequeue();
  28. }
  29.  
  30. }
  31.  
  32. class BlockingQueue<T> {
  33.  
  34. T[] contents;
  35. int capacity;
  36. static int poz = 0;
  37.  
  38. public BlockingQueue(int capacity) {
  39. contents = (T[]) new Object[capacity];
  40. this.capacity = capacity;
  41. }
  42.  
  43. public void enqueue(T item) throws InterruptedException {
  44. Sema.s.acquire();
  45. contents[poz] = item;
  46. poz++;
  47.  
  48. }
  49.  
  50. public void dequeue() {
  51. if (Sema.s.availablePermits() != capacity) {
  52. poz--;
  53. Sema.s.release();
  54. }
  55. }
  56. }
  57.  
  58. public class Main {
  59.  
  60. public static void main(String[] args) {
  61. ArrayList<Tred> tr = new ArrayList<>();
  62. Scanner s = new Scanner(System.in);
  63.  
  64. int n = s.nextInt();
  65. BlockingQueue<Integer> q = new BlockingQueue<>(n);
  66. Sema.s = new Semaphore(n);
  67.  
  68. n = s.nextInt();
  69.  
  70. for (int i = 0; i < n; i++) {
  71. Tred a = new Tred(i, q);
  72. tr.add(a);
  73. }
  74.  
  75. for (Tred r : tr) {
  76. r.start();
  77. }
  78. for (int i = 0; i < q.contents.length; i++) {
  79. System.out.println();
  80. }
  81.  
  82. }
  83.  
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement