Advertisement
Guest User

Untitled

a guest
Mar 31st, 2020
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. import java.util.concurrent.Semaphore;
  2.  
  3. public class BlockingQueue<T> extends Thread{
  4.  
  5. T[] contents;
  6. int capacity;
  7. int front;
  8. int back;
  9.  
  10. public BlockingQueue(int capacity) {
  11. contents = (T[]) new Object[capacity];
  12. this.capacity = capacity;
  13. front = back = 0;
  14. }
  15.  
  16. public void enqueue(T item) throws InterruptedException {
  17. if (this.back == this.capacity){
  18. System.out.println("The Queue is full. Item will not be added.\n"); //polna redica
  19. } else{
  20. contents[back] = item; // dodava item i go zgolemuva back za 1;
  21. back++;
  22. dequeueSemamphore.release();
  23. }
  24. }
  25. public T dequeue() throws InterruptedException {
  26. if (this.back == 0){
  27. System.out.println("Queue is empty\n");
  28. return null;
  29. } else{
  30. dequeueSemamphore.acquire();
  31. T item = contents[0];
  32. for (int i = 0; i < this.back-1; i++) {
  33. contents[i] = contents[i+1];
  34. }
  35. contents[back] = null; // brisam element sto e ostanat na krajot;
  36. this.back--;
  37. return item;
  38. }
  39. }
  40. public void print(){
  41. if (front==back){
  42. System.out.println("Queue is empty...");
  43. return;
  44. }
  45. for (int i = front; i < back; i++) {
  46. System.out.print(contents[i] + " ");
  47. }
  48. System.out.println();
  49. }
  50.  
  51. public static Semaphore dequeueSemamphore = new Semaphore(0);
  52. public static void main(String[] args) {
  53. BlockingQueue<Integer> blockingQueue = new BlockingQueue<>(100);
  54. //treba da se testira
  55. }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement