1. 程式人生 > 其它 >基於java實現一個有限阻塞式生產者消費者佇列佇列(簡單易懂)

基於java實現一個有限阻塞式生產者消費者佇列佇列(簡單易懂)

本文介紹瞭如何基於Condition實現一個有限阻塞式生產者消費者佇列:程式碼如下:

public class BoundedBlockingQueue {

AtomicInteger size = new AtomicInteger(0);
private volatile int capacity;
//自己實現阻塞佇列,需要一個容器,內部實現了一個node,如果改造為不只是int的,使用T泛型
private LinkedList<Integer> container;

//可重入鎖
private static ReentrantLock lock = new ReentrantLock();
Condition procuder = lock.newCondition();//用來通知生產(入隊)執行緒等待await還是可以執行signal
Condition consumer = lock.newCondition();//用來通知消費(出隊)執行緒等待await還是可以執行signal

public BoundedBlockingQueue(int capacity) {
this.capacity = capacity;
container = new LinkedList<>();
}

/**
* 入隊
*
* @param element
* @throws InterruptedException
*/
public void enqueue(int element) throws InterruptedException {
//每一個執行緒都會獲得鎖,但是如果條件不滿足則會阻塞
lock.lock();
try {
//阻塞的話必須用迴圈,讓這個執行緒再次獲得cpu片段的時候能夠夠執行
while (size.get() >= capacity) {
//入隊執行緒阻塞,把鎖釋放?
procuder.await();
}
container.addFirst(element);
size.incrementAndGet();

//通知出隊執行緒
consumer.signal();
} finally {
lock.unlock();
}
}

public int dequeue() throws InterruptedException {
lock.lock();
try {
while (size.get() == 0) {
consumer.await();
}
int lastValue = container.getLast();
container.removeLast();
size.decrementAndGet();

//通知入隊執行緒
procuder.signal();
return lastValue;
} finally {
lock.unlock();
}
}

public int size() {
return size.get();
}

}