五大核心参数就像餐厅运营团队:
ExecutorService executor = Executors.newFixedThreadPool(5);
ExecutorService executor = Executors.newCachedThreadPool();
ExecutorService executor = Executors.newSingleThreadExecutor();
ScheduledExecutorService executor = Executors.newScheduledThreadPool(3);
ThreadPoolExecutor executor = new ThreadPoolExecutor(
Runtime.getRuntime().availableProcessors(), // 核心=CPU核数
Runtime.getRuntime().availableProcessors(), // 最大=CPU核数
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(1000) // 有界队列防OOM
);
原理:避免过多线程上下文切换,保持CPU利用率最大化
ThreadPoolExecutor executor = new ThreadPoolExecutor(
2 * Runtime.getRuntime().availableProcessors(),
50, // 根据实际测试调整
30L, TimeUnit.SECONDS,
new SynchronousQueue<>(),
new ThreadPoolExecutor.CallerRunsPolicy()
);
原理:增加线程数应对IO等待,使用同步队列快速扩容
int corePoolSize = N * U * (1 + W/C)
// N=CPU核数 U=目标CPU利用率(0.7~0.8)
// W=等待时间 C=计算时间
示例:8核CPU,任务包含70%等待时间
corePoolSize = 8 * 0.8 * (1 + 0.7/0.3) ≈ 21
队列类型 | 特点 | 适用场景 |
---|---|---|
LinkedBlockingQueue | 无界/有界,FIFO | 已知任务量的批处理 |
SynchronousQueue | 不存储任务,直接传递 | 需要快速扩容的即时任务 |
PriorityBlockingQueue | 优先级队列 | 任务分级的调度系统 |
// 获取线程池状态
System.out.println("活跃线程数:" + executor.getActiveCount());
System.out.println("完成任务数:" + executor.getCompletedTaskCount());
// 使用Micrometer+Prometheus实现可视化监控
// 运行时修改核心线程数
executor.setCorePoolSize(20);
// 使用Apache Commons Pool实现弹性伸缩
@Bean
public ThreadPoolTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(50);
executor.setQueueCapacity(200);
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
场景特征 | 推荐线程池类型 | 关键参数配置要点 |
---|---|---|
固定并发量,怕OOM | 自定义ThreadPoolExecutor | 有界队列+合理拒绝策略 |
突发流量,快速响应 | CachedThreadPool | 控制最大线程数防失控 |
定时任务 | ScheduledThreadPool | 核心数按任务类型设置 |
资源敏感型系统 | ForkJoinPool | 使用工作窃取算法提升效率 |
记住:没有最好的线程池,只有最合适的配置。建议先用公式计算初始值,再通过压测工具(JMeter)验证调整,最终实现最优性能!