Java中Executors提供了5种线程池,本文就说一下这五种线程池。
阅读本文之前需要了解以下ThreadPoolExecutor的原理,可以看一下我之前写的一篇文章Java线程池ThreadPoolExecutor详解
1、newCachedThreadPool()
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
SynchronousQueue是一个容量为0的同步队列,当线程调用put()的时候会阻塞,直到有其他线程调用take()的时候,put()才会唤醒。如果线程调用take()的时候会阻塞,直到有其他线程调用put()的时候,take()才会苏醒。
从构造函数就可以看出,CachedThreadPool是构造了一个全是非核心线程,最大线程容量为Integer.MAX_VALUE,并且回收时间是60s,队列为SynchronousQueue。
它会试图缓存线程并重用,当无缓存线程可用时,就会创建新的工作线程;如果线程闲置的时间超过 60 秒,则被终止并移出缓存
CachedThreadPool适用于处理大量短时间工作。
2、newFixedThreadPool(int n)
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
从构造方法可以看出,FixedThreadPool采用n个核心线程,被不允许核心线程被回收,采用的是无界队列LinkedBlockingQueue。
3、newSingleThreadPool()
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
从构造函数可以看出SingleThreadPool只有一个核心线程,并不允许被回收,采用的也是无界队列LinkedBlockingQueue
4、newScheduledThreadPool()
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
可以看出底层还是创建了一个ThreadPoolExecutor,调用了核心线程数为corePoolSize,最大线程数为Integer.MAX_VALUE,任务队列采用的是DelayedWorkQueue。
ScheduledThreadPool适用于执行延迟任务。
5、newSingleScheduledThreadPool()
public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
return new DelegatedScheduledExecutorService
(new ScheduledThreadPoolExecutor(1));
}
和ScheduledThreadPool类似,只不过只有一个核心线程。
6、newWorkStealingPool()
public static ExecutorService newWorkStealingPool() {
return new ForkJoinPool
(Runtime.getRuntime().availableProcessors(),
ForkJoinPool.defaultForkJoinWorkerThreadFactory,
null, true);
}
从构造函数可以看出,生成的ForkJoinPool,适用于执行并行任务。