生产者和消费者的典型考题,用blocking queue来做。
https://zhuanlan.zhihu.com/p/84647595 讲解
启发于:java 8 源代码:https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/Condition.html
class BoundedBlockingQueue {
final Lock lock = new ReentrantLock();
final Condition notFull = lock.newCondition();
final Condition notEmpty = lock.newCondition();
private int capacity;
private Queue<Integer> queue;
public BoundedBlockingQueue(int capacity) {
this.capacity = capacity;
this.queue = new LinkedList<Integer>();
}
public void enqueue(int element) throws InterruptedException {
lock.lock();
try {
while(size() == capacity) {
notFull.await();
}
queue.offer(element);
notEmpty.signal();
} finally {
lock.unlock();
}
}
public int dequeue() throws InterruptedException {
lock.lock();
try {
while(size() == 0) {
notEmpty.await();
}
notFull.signal();
return queue.poll();
} finally {
lock.unlock();
}
}
public int size() {
return queue.size();
}
}