阅读设置
界面、侧栏和正文分别调整,自动保存。
主题切换
界面、侧栏和正文分别调整,自动保存。
java.util.concurrent.Executors 工具类提供四种常用线程池,底层均基于 ThreadPoolExecutor 实现,各自参数、队列、适用场景不同。
底层构造:
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}参数特征:
LinkedBlockingQueue,容量 Integer.MAX_VALUE。 适用场景:任务量可控、执行耗时较长,需要限制并发峰值。 ⚠️ 风险:任务大量堆积会无限占用内存,引发OOM。底层构造:
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}参数特征:
LinkedBlockingQueue。 适用场景:任务必须严格按FIFO顺序执行,不允许并发。 ⚠️ 风险:无界队列堆积任务,大量任务会OOM。底层构造:
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}参数特征:
SynchronousQueue,不存储任务,任务直接转交线程。 适用场景:任务密集、单任务执行时间短,大量短时异步任务。 ⚠️ 风险:瞬间海量任务会创建大量线程,耗尽CPU/内存资源。底层实现 ScheduledThreadPoolExecutor,继承 ThreadPoolExecutor:
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}参数特征:
DelayedWorkQueue 延时优先级队列,按任务执行时间排序;参考阿里《Java开发手册-嵩山版》【强制】规范:禁止使用Executors创建线程池,必须手动实例化ThreadPoolExecutor,规避资源耗尽风险,具体弊端如下:
手动指定七大参数,使用有界阻塞队列,配置合理最大线程与拒绝策略:
ExecutorService pool = new ThreadPoolExecutor(
8,
16,
60L,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(100), // 有界队列
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy()
);问:Executors提供哪四种线程池,各自特点?为什么生产不建议使用? 答: