看了一眼自己一年前写的多线程,真的惨不忍睹,所以重写了一遍
class BoundedBlockingQueue {
ReentrantLock mutex;
Semaphore isFull;
Semaphore isEmpty;
LinkedList<Integer> list;
public BoundedBlockingQueue(int capacity) {
isFull = new Semaphore(capacity);
mutex = new ReentrantLock();
isEmpty = new Semaphore(0);
list = new LinkedList<>();
}
public void enqueue(int element) throws InterruptedException {
isFull.acquire();
list.addFirst(element);
isEmpty.release();
}
public int dequeue() throws InterruptedException {
isEmpty.acquire();
int temp = list.removeLast();
isFull.release();
return temp;
}
public int size() {
return list.size();
}
}