常见的线程池主要有以下几个:
FixedThreadPool
定长的线程池,有限线程数。
参数设置:
它的核心线程数和最大线程数是一样的,并且使用LinkedBlockingQuene(基于链表的阻塞队列)作为阻塞队列。
源码如下:
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
原理:
这种线程池的线程数量是固定的,当任务超过核心线程数时会放在阻塞队列中,当队列满了,由于最大线程数和核心线程数相等,因此,会直接执行拒绝策略。
CachedThreadPool
缓存线程任务的线程池,基本不限制线程数(最大线程数是Integer.MAX_VALUE)
参数设置:
核心线程数是0,最大线程数是Integer.MAX_VALUE,阻塞队列是SynchronousQuene(不缓存任务的阻塞队列)
源码如下:
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
原理:
这种线程池由于核心线程数是0,任务进来会直接进入阻塞队列,但是SynchronousQuene又是一个不缓存任务的阻塞队列,因此会直接创建新线程去执行任务,如果60秒空闲,那这个线程就会被销毁。
ScheduledThreadPool
定时线程池
参数设置:
这种线程池核心线程数自定义,最大线程数是Integer.MAX_VALUE,阻塞队列是DelayedWorkQuene(优先队列),空闲线程存活时间是0。
源码如下:
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}
原理:
这种线程池的定时功能主要是通过优先队列来实现的,具体原理这里我们就不多介绍
SingleThreadExecutor
单一线程的线程池
参数设置:
这种线程池核心线程数和最大线程数都是1,阻塞队列是LinkedBlockingQuene(基于链表的阻塞队列),空闲线程存活时间是0。
源码如下:
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
原理:
和FixedThreadPool有点像,但是它的核心线程数和最大线程数都是1
适合场景:
按照提交顺序去执行线程的场景
SingleThreadScheduledExecutor
单一定时线程池
参数设置:
它相当于核心线程数为1的ScheduledThreadPool
源码如下:
public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
return new DelegatedScheduledExecutorService
(new ScheduledThreadPoolExecutor(1));
}
ForkJoinPool
用来解决父子任务有依赖的并行计算问题的
仅为个人学习观点,如有错误,欢迎批评指正