ThreadPoolExecutor 七大核心參數
new ThreadPoolExecutor(
corePoolSize, // 核心線程數,存活期同線程池,除非 allowCoreThreadTimeOut
maximumPoolSize, // 最大線程數
keepAliveTime, // 非核心線程空閒存活時間
unit, // 時間單位
workQueue, // 任務隊列(BlockingQueue)
threadFactory, // 線程工廠(可選)
handler // 拒絕策略(RejectedExecutionHandler)
)
Executors 預設工廠方法速查
newCachedThreadPool():無界隊列,線程可回收,適合大量短任務。
newFixedThreadPool(n):固定大小,有界隊列,適合穩定負載。
newSingleThreadExecutor():單線程串行,保證任務順序。
自定義線程池實戰:帶拒絕策略重試
package com.thread.test.thread;
import java.util.concurrent.*;
public class ThreadPoolFactoryTest {
public static void main(String[] args) {
ExecutorService executor = new ThreadPoolExecutor(
5, // corePoolSize
20, // maximumPoolSize
0L, TimeUnit.SECONDS, // keepAliveTime = 0,非核心線程即時回收
new LinkedBlockingQueue<>(), // 無界隊列
new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
System.out.println(">>> 拒絕策略觸發:重新提交任務");
executor.execute(r); // 簡單重試,生產環境建議記錄日誌或持久化
}
}
);
for (int i = 0; i < 100; i++) {
executor.execute(() -> {
int id = ThreadLocalRandom.current().nextInt();
System.out.println("Task " + id + " begin");
try { Thread.sleep(2000); } catch (InterruptedException ignored) {}
System.out.println("Task " + id + " end");
});
}
System.out.println("All tasks submitted");
// executor.shutdown(); // 實際使用記得關閉
}
}
關鍵設計點解析
- 核心線程 5、最大 20:突發流量時擴容至 20,平穩期回收至 5。
- keepAliveTime = 0:非核心線程任務結束即回收,節省資源。
- LinkedBlockingQueue 無界:任務堆積不會觸發拒絕,但需防止 OOM(生產環境建議有界隊列)。
- 自定義拒絕策略:示例採用「重新提交」,實際可用
CallerRunsPolicy(調用者執行)、DiscardOldestPolicy(丟棄最舊)、或持久化到資料庫/消息隊列。
監控指標建議
getActiveCount():當前活躍線程數。
getCompletedTaskCount():已完成任務總數。
getQueue().size():待執行任務堆積數。
- 拒絕次數計數器(自定義策略中累加)。
項目地址
https://github.com/windwant/threadtest