隊列 是先進先出(FIFO, First In First Out)的線性表。僅允許在隊尾插入、隊頭刪除。生活類比:排隊買票、打印任務隊列、消息中介軟體。
陣列實現中,front 和 rear 只增不減,導致邏輯上還有空閒位置卻無法入隊。解決方案:循環隊列——下標取模 capacity 實現首尾相接。
| 狀態 | 條件 | 說明 |
|---|---|---|
| 空 | front == rear | 初始狀態、出隊後 |
| 滿 | (rear + 1) % capacity == front | 犧牲一個槽位區分空/滿 |
| 元素個數 | (rear - front + capacity) % capacity |
public class CircularQueue<E> {
private final E[] elements;
private int front = 0, rear = 0;
@SuppressWarnings("unchecked")
public CircularQueue(int capacity) {
elements = (E[]) new Object[capacity + 1]; // +1 區分空滿
}
public boolean offer(E e) {
if (isFull()) return false;
elements[rear] = e;
rear = (rear + 1) % elements.length;
return true;
}
public E poll() {
if (isEmpty()) return null;
E e = elements[front];
elements[front] = null; // GC 友好
front = (front + 1) % elements.length;
return e;
}
public E peek() { return isEmpty() ? null : elements[front]; }
public boolean isEmpty() { return front == rear; }
public boolean isFull() { return (rear + 1) % elements.length == front; }
public int size() { return (rear - front + elements.length) % elements.length; }
}
| 介面/類 | 特點 | 適用場景 |
|---|---|---|
ArrayDeque | 雙端隊列、陣列、無容量上限、非線程安全 | 單線程棧/隊列、高效能 |
LinkedList | 雙向鏈表、實現 Deque、非線程安全 | 頻繁頭尾操作、記憶體不連續 |
PriorityQueue | 優先隊列、堆實現、非線程安全 | 任務調度、Top-K 問題 |
BlockingQueue | 阻塞隊列介面、多線程安全 | 生產者-消費者模型 |
LinkedBlockingQueue | 鏈表、可選容量上限 | 高併發、無界/有界緩衝 |
ArrayBlockingQueue | 陣列、固定容量、公平鎖可選 | 固定緩衝區、低延遲 |
ConcurrentLinkedQueue | 無鎖 CAS、非阻塞 | 極高併發、最終一致性 |
DelayQueue | 延遲隊列、元素實現 Delayed | 定時任務、緩存過期清理 |
ArrayDequeLinkedBlockingQueue(無界)或 ArrayBlockingQueue(有界)ConcurrentLinkedQueuePriorityQueue(單線程)或 PriorityBlockingQueue(多線程)DelayQueueBlockingQueue<Task> queue = new LinkedBlockingQueue<>(100);
// 生產者
new Thread(() -> {
while (true) {
try { queue.put(produceTask()); }
catch (InterruptedException e) { break; }
}
}).start();
// 消費者
new Thread(() -> {
while (true) {
try { Task t = queue.take(); consume(t); }
catch (InterruptedException e) { break; }
}
}).start();
offer/poll 不拋異常、返回 boolean/null,add/remove 會拋異常,根據業務選擇;