目錄:1、什麼是阻塞佇列 2、主要實作與方法 3、實作原理 4、應用:生產者—消費者 5、參考資料
佇列是一種資料結構,只有兩個基本操作:在尾部加入元素、從頭部移除元素。阻塞佇列與普通佇列的差別在於「要不要讓當前執行緒停下來」:普通佇列不會阻塞執行緒,因此面對生產者—消費者模型時,你必須自己實作同步策略與執行緒喚醒策略。而阻塞佇列天生就處理了這件事——佇列為空時,取元素的動作會被阻塞;佇列已滿時,放元素的動作也會被阻塞。
java.util.concurrent 套件提供了幾種主要實作:
Integer.MAX_VALUE。阻塞佇列包含了非阻塞佇列的大部分方法,另外還提供幾個非常實用的方法:
put:往隊尾存入元素,佇列滿則等待。take:從隊首取元素,佇列空則等待。offer:往隊尾存入元素,佇列滿則等待一段時間;時間到仍未插入成功回傳 false,否則回傳 true。poll:從隊首取元素,佇列空則等待一段時間;時間到仍取不到回傳 null,否則回傳取到的元素。先看一段程式碼:
import java.util.concurrent.ArrayBlockingQueue;
public class BlockingQueue {
public static void main(String[] args) throws InterruptedException {
java.util.concurrent.BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(5);
for (int i = 0; i < 10; i++) {
blockingQueue.put("加入元素" + i); // 將指定元素加入此佇列
System.out.println("向阻塞佇列中添加了元素:" + i);
}
System.out.println("程式到此運行結束,即將退出----");
}
}
當容量限制為 5 時,加入 5 個元素之後再繼續 put 就會在佇列外阻塞等待,此時程式並不會結束——這就是「阻塞」最直觀的證明。
若我們在佇列滿了之後把隊首元素移走,就能繼續加入:
public class BlockingQueue {
public static void main(String[] args) throws InterruptedException {
java.util.concurrent.BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(5);
for (int i = 0; i < 10; i++) {
blockingQueue.put("加入元素" + i);
System.out.println("向阻塞佇列中添加了元素:" + i);
if (i >= 4)
System.out.println("移除隊首元素" + blockingQueue.take());
}
System.out.println("程式到此運行結束,即將退出----");
}
}
下面以 ArrayBlockingQueue 為例。先看它的成員變數:
public class ArrayBlockingQueue<E> extends AbstractQueue<E>
implements BlockingQueue<E>, java.io.Serializable {
/** 底層儲存結構-陣列 */
final Object[] items;
/** 隊首元素索引 */
int takeIndex;
/** 隊尾元素索引 */
int putIndex;
/** 佇列元素總數 */
int count;
/** 重入鎖 */
final ReentrantLock lock;
/** notEmpty 等待條件 */
private final Condition notEmpty;
/** notFull 等待條件 */
private final Condition notFull;
transient Itrs itrs = null;
可見真正用來儲存元素的是一個陣列,而阻塞的關鍵則是「一把 ReentrantLock + 兩個 Condition」。
put() 的實作:
public void put(E e) throws InterruptedException {
checkNotNull(e); // 先檢查 e 是否為空
final ReentrantLock lock = this.lock;
lock.lockInterruptibly(); // 取得鎖
try {
while (count == items.length) // 佇列已滿,進入條件等待
notFull.await();
enqueue(e); // 佇列不滿,執行入隊
} finally {
lock.unlock(); // 釋放鎖
}
}
具體的入隊操作:
private void enqueue(E x) {
final Object[] items = this.items;
items[putIndex] = x; // 隊尾入隊
if (++putIndex == items.length)
putIndex = 0; // 環形陣列,回到頭
count++;
notEmpty.signal(); // 通知等待 notEmpty 的執行緒
}
take() 的實作:
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == 0) // 佇列為空
notEmpty.await(); // 執行緒加入 notEmpty 等待集
return dequeue(); // 非空,出隊
} finally {
lock.unlock();
}
}
把上面三段放在一起看,整個機制就很清楚了:用一把鎖保證互斥,用兩個條件變數分別表達「非空」與「非滿」,生產者與消費者各自在對應條件上等待,任何一方推進佇列後就通知另一方。這也正是為什麼用阻塞佇列實作生產者—消費者,不需要自己寫 wait/notify。
public class Test {
private int queueSize = 10;
private ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(queueSize);
public static void main(String[] args) {
Test test = new Test();
Producer producer = test.new Producer();
Consumer consumer = test.new Consumer();
producer.start();
consumer.start();
}
class Consumer extends Thread {
@Override
public void run() {
consume();
}
private void consume() {
while (true) {
try {
queue.take();
System.out.println("從佇列取走一個元素,佇列剩餘" + queue.size() + "個元素");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Producer extends Thread {
@Override
public void run() {
produce();
}
private void produce() {
while (true) {
try {
queue.put(1);
System.out.println("向佇列中插入一個元素,佇列剩餘空間:" + (queueSize - queue.size()));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
整段程式沒有一個 synchronized、沒有一組 wait/notify,卻能正確地協調兩個執行緒——這就是阻塞佇列的價值所在。
《Java 並發編程藝術》、《Effective Java》以及 JDK 原始碼 java.util.concurrent.ArrayBlockingQueue。