1、概述:
线程池类型 | 用途说明 | 适用场景 |
---|---|---|
Executors.newFixedThreadPool | 创建固定线程数的线程池,使用的是LinkedBlockingQueue无界队列,线程池中实际线程数永远不会变化 | 适用于可以预测线程数量的业务中,或者服务器负载较重,对线程数有严格限制的场景 |
Executors.newSingleThreadExecutor | 创建只有一个线程的线程池,使用的是LinkedBlockingQueue无界队列,线程池中实际线程数只有一个 | 适用于需要保证顺序执行各个任务,并且在任意时间点,不会同时有多个线程的场景 |
Executors.newCachedThreadPool | 创建可供缓存的线程池,该线程池中的线程空闲时间超过60s会自动销毁,使用的是SynchronousQueue特殊无界队列 | 适用于创建一个可无限扩大的线程池,服务器负载压力较轻,执行时间较短,任务多的场景 |
Executors.newScheduledThreadPool | 创建可供调度使用的线程池(可延时启动,定时启动),使用的是DelayWorkQueue无界延时队列 | 适用于需要多个后台线程执行周期任务的场景 |
Executors.newWorkStealingPool | jdk1.8提供的线程池,底层使用的是ForkJoinPool实现,创建一个拥有多个任务队列的线程池,可以减少连接数,创建当前可用cpu核数的线程来并行执行任务 | 适用于大耗时,可并行执行的场景 |
2、创建方法:
newFixedThreadPool
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads,
nThreads,
0L,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
newSingleThreadExecutor
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1,
1,
0L,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
newCachedThreadPool
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0,
Integer.MAX_VALUE,
60L,
TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
newScheduledThreadPool
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize,
ThreadFactory threadFactory) {
return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
}
newWorkStealingPool
public static ExecutorService newWorkStealingPool(int parallelism) {
return new ForkJoinPool(parallelism,
ForkJoinPool.defaultForkJoinWorkerThreadFactory,
null,
true);
}