在 Java 開發中,模擬打印機隊列是理解生產者-消費者模式、單例模式以及線程同步機制的經典案例。本文將深入解析一個基於 LinkedList 實現的打印任務分發器,展示如何通過雙重檢查鎖定實現線程安全的單例,以及如何管理任務的添加、優先插入與順序執行。
DataDistribute 類採用單例模式,確保整個應用中只存在一個任務分發中心。其核心字段包括:
tasks:LinkedList<DataDistributeEntity>,存儲待打印任務隊列isClose:標誌分發器是否關閉obj:字節數組鎖對象,用於同步控制public static DataDistribute getInstance() {
if (instance == null) {
synchronized (obj) {
if (instance == null) {
instance = new DataDistribute();
}
}
}
return instance;
}
採用雙重檢查鎖定(Double-Checked Locking)模式,在保證線程安全的前提下避免不必要的同步開銷,是高併發場景下的經典寫法。
提供兩種添加任務的方式:
addFirst),實現緊急任務優先處理兩者均在 synchronized (obj) 塊中操作,保證隊列修改的原子性。
public void start(ICallBack callback) {
if (tasks == null || tasks.isEmpty() || !this.isClose) return;
this.isClose = false;
while (true) {
DataDistributeEntity entity = tasks.poll();
if (entity == null) {
this.isClose = true;
break;
}
callback.call(entity);
tasks.remove(entity);
}
System.out.println("fsf");
}
start 方法輪詢隊列,通過回調接口 ICallBack 執行具體打印邏輯。隊列為空時自動關閉分發器,體現了生產者-消費者模式的基本流程。
PriorityQueue)支持多級優先級這個模擬器雖然簡潔,但涵蓖了 Java 併發編程的多個核心知識點,是學習線程安全集合操作、單例模式及回調機制的優秀教學案例。