Advertisement
Guest User

Untitled

a guest
Mar 31st, 2020
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.14 KB | None | 0 0
  1. package lab2;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Arrays;
  5. import java.util.List;
  6. import java.util.concurrent.Semaphore;
  7.  
  8. public class BlockingQueue<T> {
  9. Semaphore e = new Semaphore(1);
  10. Semaphore d = new Semaphore(1);
  11. T[] contents;
  12. int capacity;
  13.  
  14. public BlockingQueue(int capacity) {
  15. contents = (T[]) new Object[capacity];
  16. this.capacity = capacity;
  17. }
  18.  
  19. @Override
  20. public String toString() {
  21. return Arrays.toString(contents) ;
  22. }
  23.  
  24. public void enqueue(T item) throws InterruptedException {
  25. e.acquire();
  26. T[] temp = (T[]) new Object[capacity+1];
  27. if (capacity >= 0) System.arraycopy(contents, 0, temp, 0, capacity);
  28. temp[capacity++]=item;
  29. this.contents = temp;
  30. System.out.println("e");
  31. e.release();
  32. }
  33. public void dequeue() throws InterruptedException {
  34. d.acquire();
  35. T [] temp = (T[]) new Object[capacity-1];
  36. if (capacity >= 0) System.arraycopy(contents, 0, temp, 0, capacity-1);
  37. this.contents= temp;
  38. this.capacity--;
  39. System.out.println("d");
  40. d.release();
  41. }
  42. public static void main(String[] args) throws InterruptedException {
  43. BlockingQueue<Integer> bq = new BlockingQueue<>(2);
  44. List<Thread> list = new ArrayList<>(5);
  45. Thread t0 = new Thread(new Runnable() {
  46. @Override
  47. public void run() {
  48. try {
  49. bq.enqueue(30);
  50. } catch (InterruptedException ex) {
  51. ex.printStackTrace();
  52. }
  53. }
  54. });
  55. list.add(t0);
  56. Thread t1 = new Thread(new Runnable() {
  57. @Override
  58. public void run() {
  59. try {
  60. bq.enqueue(20);
  61. } catch (InterruptedException ex) {
  62. ex.printStackTrace();
  63. }
  64. }
  65. });
  66. list.add(t1);
  67. Thread t2 = new Thread(new Runnable() {
  68. @Override
  69. public void run() {
  70. try {
  71. bq.enqueue(5);
  72. } catch (InterruptedException ex) {
  73. ex.printStackTrace();
  74. }
  75. }
  76. });
  77. list.add(t2);
  78. Thread t3 = new Thread(new Runnable() {
  79. @Override
  80. public void run() {
  81. try {
  82. bq.dequeue();
  83. } catch (InterruptedException ex) {
  84. ex.printStackTrace();
  85. }
  86. }
  87. });
  88. list.add(t3);
  89. Thread t4 = new Thread(new Runnable() {
  90. @Override
  91. public void run() {
  92. try {
  93. bq.dequeue();
  94. } catch (InterruptedException ex) {
  95. ex.printStackTrace();
  96. }
  97. }
  98. });
  99. list.add(t4);
  100. for( Thread t : list){
  101. t.start();
  102. }
  103. for( Thread t : list){
  104. t.join();
  105. }
  106. System.out.println(bq.toString());
  107. }
  108.  
  109.  
  110. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement