一、Executors 工具类概述
Executors 是 Java 并发包 (java.util.concurrent) 中的一个工具类,
提供了一系列静态工厂方法,用于快速创建不同类型的线程池。
这些方法内部封装了 ThreadPoolExecutor 或 ScheduledThreadPoolExecutor 的配置,
简化了线程池的创建过程。
二、Executors 提供的线程池类型及用法
工厂方法 | 线程池类型 | 核心参数配置 | 适用场景 | 潜在问题 |
---|---|---|---|---|
newFixedThreadPool(int n) | 固定大小线程池 | - 核心线程数 = 最大线程数 = n - 任务队列: LinkedBlockingQueue (无界队列) | CPU 密集型任务,需限制线程数 | 无界队列可能导致任务堆积,引发 OOM |
newCachedThreadPool() | 可缓存线程池 | - 核心线程数 = 0 - 最大线程数 = Integer.MAX_VALUE - 存活时间 60 秒 - 队列: SynchronousQueue | 短期异步任务,高并发且任务轻量 | 线程数可能无限增长,导致资源耗尽 |
newSingleThreadExecutor() | 单线程线程池 | - 核心线程数 = 最大线程数 = 1 - 任务队列: LinkedBlockingQueue (无界队列) | 需任务顺序执行(如日志写入) | 无界队列可能导致任务堆积 |
newScheduledThreadPool(int n) | 定时/周期性任务线程池 | - 核心线程数 = n - 任务队列: DelayedWorkQueue | 定时任务、周期性任务(如心跳检测) | 需合理设置核心线程数,避免资源浪费 |
newWorkStealingPool(int n) | 工作窃取线程池 | - 并行级别 = n (默认 CPU 核心数)- 内部使用 ForkJoinPool | 可拆分的并行任务(如分治算法) | 不适用于阻塞型任务 |
所有 Executors 创建的线程池本质上是 ThreadPoolExecutor 或 ScheduledThreadPoolExecutor 的实例,只是通过不同参数配置实现不同特性:
三、Executors 与 ThreadPoolExecutor 的内在关系
源码分析
newFixedThreadPool:
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(
nThreads, // corePoolSize
nThreads, // maximumPoolSize
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>() // 无界队列
);
}
newCachedThreadPool:
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(
0, // corePoolSize
Integer.MAX_VALUE, // maximumPoolSize
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>() // 直接传递队列
);
}
newSingleThreadExecutor:
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService(
new ThreadPoolExecutor(
1, 1, 0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()
)
);
}
newScheduledThreadPool:
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
// ScheduledThreadPoolExecutor 继承自 ThreadPoolExecutor,使用 DelayedWorkQueue
四、为什么推荐手动创建 ThreadPoolExecutor?
无界队列风险
newFixedThreadPool 和 newSingleThreadExecutor 使用无界队列 LinkedBlockingQueue,
任务可能无限堆积,导致OOM。
线程数失控
newCachedThreadPool 允许最大线程数为 Integer.MAX_VALUE,高并发时可能创建大量线程,耗尽系统资源。
拒绝策略不可控
默认拒绝策略为 AbortPolicy(抛出异常),但实际业务可能需要更友好的处理方式(如降级、日志记录)。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。