頻繁 `new Thread()` 弊端明顯:
線程池優勢:線程複用、並發數控制、任務隊列緩衝、豐富調度策略。
// 簡化結構
public class ThreadPoolExecutor extends AbstractExecutorService {
private final BlockingQueue workQueue; // 任務隊列
private final HashSet workers; // 工作線程集合
// Worker 實現 Runnable,run() 中循環 takeTask() 執行
}
| 方法類別 | 拋出異常 | 返回特殊值 | 阻塞等待 | 超時等待 |
|---|---|---|---|---|
| 插入 | `add(e)` | `offer(e)` | `put(e)` | `offer(e, time, unit)` |
| 移除 | `remove()` | `poll()` | `take()` | `poll(time, unit)` |
| 檢查 | `element()` | `peek()` | 不可用 | 不可用 |
// 經典配置範本
// CPU 密集:core = max = Ncpu + 1,有界隊列
// IO 密集:core = 2*Ncpu,max = 4*Ncpu,無界/同步隊列
ExecutorService pool = new ThreadPoolExecutor(
corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(1000), // 有界,防 OOM
new ThreadFactoryBuilder().setNameFormat("biz-%d").build(), // 命名
new ThreadPoolExecutor.CallerRunsPolicy() // 背壓
);
final void runWorker(Worker w) {
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // 釋放鎖,允許中斷
try {
while (task != null || (task = getTask()) != null) {
w.lock(); // 執行任務前加鎖 (可中斷)
try {
beforeExecute(w.thread, task);
task.run();
afterExecute(task, null);
} finally {
task = null;
w.unlock();
}
}
} finally {
processWorkerExit(w, completedAbruptly);
}
}
// 獲取任務:阻塞/超時/關閉檢查
private Runnable getTask() {
for (;;) {
int wc = workerCountOf(ctl.get());
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
if (wc > maximumPoolSize || (timed && timedOut))
return null; // 線程退出
Runnable r = timed ? workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS)
: workQueue.take();
if (r != null) return r;
}
}
| 指標 | 獲取方式 | 告警閾值建議 |
|---|---|---|
| 活躍線程數 | `getActiveCount()` | > 80% maxPoolSize 持續 5min |
| 隊列堆積數 | `getQueue().size()` | > 70% 隊列容量 或 持續增長 |
| 任務完成率 | `getCompletedTaskCount() / getTaskCount()` | < 95% (含拒絕/異常) |
| 拒絕次數 | 自定義 `RejectedExecutionHandler` 計數 | > 0 即告警 |
| 線程存活時間 | JFR / Arthas `thread -n | 非核心線程頻繁創建銷毀 |
`ThreadPoolExecutor` + `BlockingQueue` 是 Java 併發編程的基石。理解「參數如何影響擴容/縮容」、「隊列特性如何決定背壓行為」、「Worker 循環如何處理中斷/異常/退出」,才能從「配置參數」進階到「架構決策」。下一篇將實戰《動態線程池:基於配置中心的運行時參數熱更新與自適應擴縮容》。