本文主要是介绍Blocking Queue,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
生产者和消费者的典型考题,用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();}
}
这篇关于Blocking Queue的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!