Java 集合框架提供豐富的隊列實現,按特性分類:
| 類別 | 特性 |
|---|---|
| ArrayDeque | 數組雙端隊列,非線程安全 |
| PriorityQueue | 優先級隊列,非線程安全 |
| ConcurrentLinkedQueue | 基於鏈表的無界並發隊列 |
| DelayQueue | 延遲阻塞隊列 |
| ArrayBlockingQueue | 基於數組的有界阻塞隊列(FIFO) |
| LinkedBlockingQueue | 基於鏈表的有界/無界阻塞隊列 |
| LinkedBlockingDeque | 雙端阻塞隊列 |
| PriorityBlockingQueue | 帶優先級的無界阻塞隊列 |
| SynchronousQueue | 零容量同步移交隊列 |
final E[] items:固定大小數組,存儲元素;int takeIndex:出隊索引(頭部);int putIndex:入隊索引(尾部);int count:當前元素數量;ReentrantLock lock:獨佔鎖,保證線程安全;Condition notEmpty, notFull:等待/通知機制,分別對應消費者、生產者條件。final int inc(int i) {
return (++i == items.length) ? 0 : i; // 索引環繞
}
private void insert(E x) {
items[putIndex] = x;
putIndex = inc(putIndex);
++count;
notEmpty.signal(); // 喚醒消費者
}
private E extract() {
E x = items[takeIndex];
items[takeIndex] = null; // 幫助 GC
takeIndex = inc(takeIndex);
--count;
notFull.signal(); // 喚醒生產者
return x;
}
構造函數 ArrayBlockingQueue(int capacity, boolean fair) 通過 ReentrantLock(fair) 控制:
fair=false(預設):非公平鎖,吞吐量高但可能導致線程飢餓;fair=true:公平鎖,FIFO 獲取鎖,降低吞吐量但避免飢餓。| 方法 | 行為 | 阻塞/異常 |
|---|---|---|
| add(e) | 插入尾部 | 滿拋 IllegalStateException |
| offer(e) | 插入尾部 | 滿返回 false |
| put(e) | 插入尾部 | 滿阻塞等待 |
| offer(e, timeout, unit) | 插入尾部 | 超時返回 false |
| poll() | 獲取並移除頭部 | 空返回 null |
| take() | 獲取並移除頭部 | 空阻塞等待 |
| poll(timeout, unit) | 獲取並移除頭部 | 超時返回 null |
| peek() | 查看頭部不移除 | 空返回 null |
ThreadPoolExecutor 默認使用);ConcurrentLinkedQueue(無界、無鎖);PriorityBlockingQueue;掌握 ArrayBlockingQueue 的鎖機制、條件變量協作與環形數組設計,能為高併發系統的穩定性與性能調優提供堅實基礎。