ThreadPoolExecutor只是java对线程池最原始的实现,java还提供了不同特性的封装好的线程池来供我们使用。
Executors工具类提供了一系列静态工厂方法来帮助我们创建不同特性的线程池。
1、FixedThreadPool:
Executor executor = Executors.newFixedThreadPool(3);
这是一种线程数量固定的线程池,它的线程都是核心线程。看源码:
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
这就是一个核心线程数和最大线程数一样的线程池,并且没有超时时间,而且任务队列也没有限制,这样的任务队列最大值为Integer.MAX_VALUE,相当于没有限制。那么说明这个线程池的线程会等待随时响应执行任务,并且在没有线程可用的情况下,存入队列等待执行。
2、CacheThreadPool :
Executor executor2 = Executors.newCachedThreadPool();
这个线程池没有核心线程,具有不固定数量的非核心线程。看源码:
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
这就是一个没有核心线程,并且非核心线程可以是Integer.MAX_VALUE大的线程池,并且超时时间为60S,而且任务队列为SynchronousQuene,这个队列可以理解为一个不可以存储元素的队列,在这当它没用就行了。所以这个线程池的特点就是适合做一些大量的短时的任务。等到没有任务的时候,超过空闲时间,这个线程池就会关闭的。
3、ScheduledThreadPool
调度线程池,具有指定个数个核心线程,Integer.MAX_VALUE个非核心线程数,并且可以延迟执行任务,也就是相当于定时和周期性执行任务。源码:
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}
ScheduledThreadPool 是继承自ThreadPoolExecutor,所以super代表的是调用父类构造函数呗,队列是一个延时任务队列。
4、SingleThreadExecutor:
Executors.newSingleThreadExecutor();
直接看源码:
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
创建一个核心线程数和最大线程数都为1的线程池,并且么有超时时间,阻塞队列为无限大。
所以这就是一个单例线程呗。