在 Java 並發編程中,頻繁創建和銷毀線程會帶來巨大的性能開銷。java.util.concurrent.Executors 工廠類提供了多種預定義的線程池實現,幫助開發者高效管理線程生命週期。本文將深入解析三種核心線程池的特性、適用場景,並通過實戰代碼演示如何結合 ThreadFactory 定制線程屬性。
創建方式: Executors.newCachedThreadPool()
特點:
實戰輸出分析: 提交 5 個任務時,線程創建與執行交替進行,體現「按需創建、空閒回收」特性。
創建方式: Executors.newFixedThreadPool(int nThreads)
特點:
實戰輸出分析: 核心線程數設為 2 時,前 2 個任務立即執行,其餘任務排隊等待,所有線程在池創建時即完成初始化。
創建方式: Executors.newSingleThreadExecutor()
特點:
通過實現 ThreadFactory 接口,可在線程創建時注入自定義屬性:
public class DaemonThreadFactory implements ThreadFactory {
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setDaemon(true); // 設置為守護線程
return t;
}
}
// 最高優先級
public class MaxPriorityThreadFactory implements ThreadFactory {
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setPriority(Thread.MAX_PRIORITY);
return t;
}
}
// 最低優先級
public class MinPriorityThreadFactory implements ThreadFactory {
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setPriority(Thread.MIN_PRIORITY);
return t;
}
}
ExecutorService daemonExec = Executors.newCachedThreadPool(new DaemonThreadFactory());
ExecutorService maxPriorityExec = Executors.newCachedThreadPool(new MaxPriorityThreadFactory());
ExecutorService minPriorityExec = Executors.newCachedThreadPool(new MinPriorityThreadFactory());
// 不同業務場景使用不同屬性的線程池
shutdown() + awaitTermination() 確保任務完成Executors 提供了三種經典線程池,分別解決不同並發場景需求。結合 ThreadFactory 可實現線程屬性的精細化控制。實際項目中,建議基於 ThreadPoolExecutor 手動配置核心參數(corePoolSize、maximumPoolSize、keepAliveTime、workQueue、threadFactory、handler),構建更符合業務特性的高性能線程池。