Java多种类型的线程池简单介绍
Executors
核心都是 ThreadPoolExecutor
ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler
) ;
主要参数:
- corePoolSize 核心线程数:内部线程数,包括空闲线程
- maximumPoolSize 最大线程数:允许的最大线程数
- keepAliveTime 空闲保留时间:当超过核心线程数之后,空闲线程等待新任务的时间
- unit 单位:keepAliveTime的时间单位
- workQueue 工作队列:存储待执行的任务
- threadFactory 线程工厂:用来创建一个新线程
- handler/rejectHandler :处理线程边界或者达到工作队列上限的情况
#多种线程池
###1. 固定线程数
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
线程数固定,工作队列是链表,长度不固定。
如果所有线程都是活动状态,新提交的任务会一直等待,直到队列中有可用线程;
任意个线程如果应为异常而执行失败,在关闭之前另一个线程会接任执行后续任务;
###2. 单线程连接池
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
有且仅有一个线程作为工作线程,在执行完毕前异常,则由另一个线程接任;同时线程保存在一个缓冲队列里,是一个链表队列;可以实现顺序的线程执行;
###3. 缓冲队列
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
总结来说,就是按需使用,活动重用。适合在一些生命周期很短的异步场景下,此处的队列也是一个异步队列;超过60秒没有使用则从缓存移除;
###4. 可调度队列
public static ScheduledExecutorService newScheduledThreadPool(
int corePoolSize, ThreadFactory threadFactory) {
return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
}
提供一种可以延迟运行或周期运行的线程池,基于ScheduledThreadPoolExecutor实现,包括一些默认值:
public ScheduledThreadPoolExecutor(int corePoolSize,
ThreadFactory threadFactory) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue(), threadFactory);
}
注意工作队列使用new DelayedWorkQueue(),此处单独做介绍。
1.8 forkJoinPool