[Java 并发编程] 21. 阻塞队列

2020-09-04

1. 阻塞队列(Blocking Queues)

Blocking Queues 是当你尝试从一个空队列取出一个元素时、或尝试从一个满队列做插入一个元素时会被阻塞的队列。

包含:

  • 一个线程尝试从空队列做出队操作时会被阻塞,直到其他线程插入一个元素至队列中。
  • 一个线程尝试从满队列做入队操作时会被阻塞,直到其他线程消耗队列中的一个或多个元素、或清空队列。

Java 5 提供了 java.util.concurrent.BlockingQueue 的实现。

2. BlockingQueues的实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* @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();
}

}