一、阻塞队列(Blocking Queues)
Blocking Queues 是当你尝试从一个空队列取出一个元素时、或尝试从一个满队列做插入一个元素时会被阻塞的队列。
包含:
- 一个线程尝试从空队列做出队操作时会被阻塞,直到其他线程插入一个元素至队列中。
- 一个线程尝试从满队列做入队操作时会被阻塞,直到其他线程消耗队列中的一个或多个元素、或清空队列。
Java 5 提供了 java.util.concurrent.BlockingQueue 的实现。
二、BlockingQueues的实现
/**
* @author : sungm
* @date : 2020-09-04 16:31
*/
public class BlockingQueue<T> {
private LinkedList<T> queue = new LinkedList<>();
private int limit = 16;
/**
* 构造方法注入阻塞队列的上线
*
* @param limit 阻塞队列的限制
*/
public BlockingQueue(int limit) {
this.limit = limit;
}
/**
* 入队操作
*
* @param node 入队元素
* @return boolean 结果
* @throws InterruptedException e
*/
public synchronized boolean enqueue(T node) throws InterruptedException {
while (queue.size() == limit) {
wait();
}
notifyAll();
return queue.add(node);
}
/**
* 出队操作
*
* @return T 出队元素
* @throws InterruptedException e
*/
public synchronized T dequeue() throws InterruptedException {
while (queue.size() == 0) {
wait();
}
notifyAll();
//第一个元素出队并删除引用
return queue.removeFirst();
}
}