頻繁建立/銷毀執行緒開銷大(T1 + T3),且無限制建立導致記憶體耗盡或上下文切換風暴。執行緒池透過複用執行緒攤銷建立成本,並以有界隊列實現背壓,保護系統穩定性。
ThreadPoolExecutor
├── corePoolSize // 核心執行緒數(常駐)
├── maximumPoolSize // 最大執行緒數(含非核心)
├── keepAliveTime // 非核心執行緒閒置存活時間
├── workQueue // 任務隊列(有界/無界/優先級/同步移交)
├── threadFactory // 執行緒命名、優先級、守護屬性
└── RejectedExecutionHandler // 拒絕策略(Abort/Discard/CallerRuns)
public class SimpleThreadPool {
private final List<WorkerThread> workers = new ArrayList<>();
private final BlockingQueue<Runnable> taskQueue;
public SimpleThreadPool(int n, int queueCap) {
taskQueue = new LinkedBlockingQueue<>(queueCap);
for (int i=0; i<n; i++) {
WorkerThread wt = new WorkerThread(taskQueue);
wt.start();
workers.add(wt);
}
}
public void execute(Runnable task) { taskQueue.offer(task); }
public void shutdown() { workers.forEach(WorkerThread::shutdown); }
private static class WorkerThread extends Thread {
private final BlockingQueue<Runnable> q;
private volatile boolean running = true;
WorkerThread(BlockingQueue<Runnable> q) { this.q = q; }
@Override public void run() {
while (running) {
try { q.take().run(); }
catch (InterruptedException e) { break; }
catch (Exception e) { e.printStackTrace(); }
}
}
void shutdown() { running = false; interrupt(); }
}
}
ThreadPoolExecutor| 工廠方法 | 特性 | 適用場景 | 風險 |
|---|---|---|---|
newFixedThreadPool | core=max,無界 LinkedBlockingQueue | 長生命周期、任務量可控 | 隊列堆積 OOM |
newCachedThreadPool | core=0,max=Integer.MAX,SynchronousQueue | 大量極短任務 | 無限建立執行緒 OOM |
newSingleThreadExecutor | 單執行緒串行,保證順序 | 需序列化的任務 | 單點瓶頸 |
newScheduledThreadPool | 支援定時/週期任務 | 定時作業 | 同 FixedThreadPool |
corePoolSize = CPU 核心數 + 1,減少上下文切換。corePoolSize = CPU 核心數 * (1 + 平均等待時間/平均工作時間),經驗值 2×CPU。new LinkedBlockingQueue<>(capacity),防止任務堆積撐爆記憶體。CallerRunsPolicy: 由提交者執行緒執行任務,自然實現背壓減速。new ThreadFactoryBuilder().setNameFormat("order-processor-%d").build()(Guava),利於日誌追蹤。getActiveCount()、getQueue().size()、getCompletedTaskCount() 至 Prometheus。setCorePoolSize()、setMaximumPoolSize(),配合配置中心實現熱更新。Thread.setDefaultUncaughtExceptionHandler 或覆寫 afterExecute 記錄任務異常。執行緒池是高併發系統的基石。理解其七大參數交互關係、選擇適合業務的隊列與拒絕策略、建立完善監控體系,才能在流量洪峰下守住穩定防線。