Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.concurrent.Semaphore;
- public class BlockingQueue<T> extends Thread{
- T[] contents;
- int capacity;
- int front;
- int back;
- public BlockingQueue(int capacity) {
- contents = (T[]) new Object[capacity];
- this.capacity = capacity;
- front = back = 0;
- }
- public void enqueue(T item) throws InterruptedException {
- if (this.back == this.capacity){
- System.out.println("The Queue is full. Item will not be added.\n"); //polna redica
- } else{
- contents[back] = item; // dodava item i go zgolemuva back za 1;
- back++;
- dequeueSemamphore.release();
- }
- }
- public T dequeue() throws InterruptedException {
- if (this.back == 0){
- System.out.println("Queue is empty\n");
- return null;
- } else{
- dequeueSemamphore.acquire();
- T item = contents[0];
- for (int i = 0; i < this.back-1; i++) {
- contents[i] = contents[i+1];
- }
- contents[back] = null; // brisam element sto e ostanat na krajot;
- this.back--;
- return item;
- }
- }
- public void print(){
- if (front==back){
- System.out.println("Queue is empty...");
- return;
- }
- for (int i = front; i < back; i++) {
- System.out.print(contents[i] + " ");
- }
- System.out.println();
- }
- public static Semaphore dequeueSemamphore = new Semaphore(0);
- public static void main(String[] args) {
- BlockingQueue<Integer> blockingQueue = new BlockingQueue<>(100);
- //treba da se testira
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement