核心架構三類別
- TestThreadPool:測試主程式,模擬客戶請求
- ThreadPoolManager:池管理器,負責初始化與分派
- SimpleThread:工作執行緒,實際處理任務
完整實作程式碼
SimpleThread.java (工作執行緒)
class SimpleThread extends Thread {
private boolean running = false;
private String task;
SimpleThread(int id) {
super("Worker-" + id);
System.out.println(getName() + " 已啟動");
}
synchronized void assign(String task) {
this.task = task;
this.running = true;
notify(); // 喚醒等待中的執行緒
}
synchronized boolean isIdle() { return !running; }
public void run() {
try {
while (true) {
synchronized (this) {
while (!running) wait(); // 閒置等待
}
// 處理任務
System.out.println(getName() + " 處理: " + task + " ... 完成");
Thread.sleep(5000); // 模擬耗時操作
System.out.println(getName() + " 進入閒置");
synchronized (this) { running = false; }
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
ThreadPoolManager.java (管理器)
class ThreadPoolManager {
private final List workers = new ArrayList<>();
ThreadPoolManager(int size) {
for (int i = 1; i <= size; i++) {
SimpleThread t = new SimpleThread(i);
workers.add(t);
t.start();
}
}
void process(String task) {
for (SimpleThread t : workers) {
if (t.isIdle()) {
t.assign(task);
return;
}
}
System.out.println("執行緒池已滿,請稍後再試");
}
}
TestThreadPool.java (測試)
public class TestThreadPool {
public static void main(String[] args) throws IOException {
ThreadPoolManager pool = new ThreadPoolManager(10);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input;
while ((input = br.readLine()) != null) {
pool.process(input);
}
}
}
關鍵機制解析
- wait/notify:執行緒在
wait() 釋放鎖進入等待集合,notify() 喚醒一個執行緒重新競爭鎖
- synchronized 保護:wait/notify 必須在同步區塊內,否則拋出
IllegalMonitorStateException
- 狀態旗標:
running 區分閒置/忙碌,避免虛假喚醒
- while 迴圈檢查:
while (!running) wait() 防止虛假喚醒
生產級改進方向
- 使用
BlockingQueue 替代手工分派
- 採用
ThreadPoolExecutor 內建拒絕策略
- 支援動態調整核心/最大執行緒數
- 加入任務逾時、監控指標、優雅關閉
- 使用
CompletableFuture 非阻塞組合