隊列(FIFO)核心操作:入隊、出隊、查首、判空、清空、查找。Java Vector 內建同步、動態擴容、隨機訪問,是構建線程安全隊列的理想基底。本文給出生產級參考實現。
public class EmptyQueueException extends RuntimeException {
public EmptyQueueException() { super("Queue is empty"); }
public EmptyQueueException(String msg) { super(msg); }
}
public interface Queue {
void enq(E x); // 入隊
E deq(); // 出隊
E front(); // 查首不移除
boolean empty(); // 判空
void clear(); // 清空
int search(E x); // 查找位置(0-based),不存在返回 -1
}
public class VectorQueue implements Queue {
private final Vector data = new Vector<>();
@Override
public synchronized void enq(E x) {
data.addElement(x);
}
@Override
public synchronized E deq() {
if (empty()) throw new EmptyQueueException();
E x = data.elementAt(0);
data.removeElementAt(0);
return x;
}
@Override
public synchronized E front() {
if (empty()) throw new EmptyQueueException();
return data.elementAt(0);
}
@Override
public boolean empty() {
return data.isEmpty();
}
@Override
public synchronized void clear() {
data.removeAllElements();
}
@Override
public int search(E x) {
return data.indexOf(x); // Vector.indexOf 返回 0-based 索引
}
}
| 實現 | 入隊 | 出隊 | 線程安全 | 備註 |
|---|---|---|---|---|
| Vector/ArrayList + synchronized | O(1) 攤銷 | O(n) 需位移 | 粗粒度鎖 | 教學/低併發 |
| LinkedList + synchronized | O(1) | O(1) | 粗粒度鎖 | 高頻出隊優選 |
| ArrayDeque (非線程安全) | O(1) | O(1) | 無 | 單線程最高性能 |
| ConcurrentLinkedQueue | O(1) | O(1) | 無鎖 CAS | 高併發生產環境首選 |
| ArrayBlockingQueue | O(1) 可阻塞 | O(1) 可阻塞 | ReentrantLock | 有界緩衝、生產消費者模式 |
java.util.concurrent 包:ConcurrentLinkedQueue(無界)、ArrayBlockingQueue(有界)、LinkedBlockingQueue。LinkedList 做底層,避免 Vector.removeElementAt(0) 的 O(n) 位移開銷。EmptyQueueException 繼承 RuntimeException,調用方可選捕獲,符合「異常即 Bug」原則。理解隊列底層實現差異,能在面試、架構選型、性能調優時做出精準決策。生產代碼請直接擁抱 JUC。