- ExecutorService的创建
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
·····
}
- corePoolSize:核心线程数,除非设置了allowCoreThreadTimeOut,否则要保留在池中的线程数(即使它们是空闲的)。
- maximumPoolSize: 池中允许的最大线程数
- keepAliveTime: 非核心线程等待新任务的最大时间,超过存活时间的非核心线程将会被回收。
- unit: 存活时间的时间单位
- workQueue: 任务队列,存储暂时无法执行的任务,等待空闲线程来执行任务
- threadFactory: 线程工厂,用于创建线程。默认使用DefaultThreadFactory
-
handler: 当线程边界和任务队列容量已经达到最大时,用于处理阻塞时的程序。默认AbortPolicy,它会抛出RejectedExecutionException
补充:
BlockingQueue 主要的实现类:- LinkedBlockingDeque
是一个用链表实现的有界阻塞队列,容量可以选择进行设置,不设置的话,将是一个无边界的阻塞队列,最大长度为Integer.MAX_VALUE。 - ArrayBlockingQueue
是一个用数组实现的有界阻塞队列,必须设置容量。
- LinkedBlockingDeque
- 线程池的类型
2.1 可缓存线程池
创建方式:
ExecutorService executorService = Executors.newCachedThreadPool();
原理是:
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
不推荐使用Executors.newCachedThreadPool()创建可缓存线程池。
推荐使用自定义的方式
ExecutorService executorService = new ThreadPoolExecutor(0, 100, 60, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(1000));
2.2 单线程池
//不推荐使用
ExecutorService executorService = Executors.newSingleThreadExecutor();
//推荐使用
new ThreadPoolExecutor(1,1,0,TimeUnit.SECONDS, new ArrayBlockingQueue<>(1000));
2.3 固定线程数线程池
//不推荐使用
ExecutorService executorService = Executors.newFixedThreadPool(20);
//推荐使用
new ThreadPoolExector(20,20,0,TimeUnit.SECONDS,new ArrayBlockingQueue<>(1000));
2.4 支持定时和周期的线程池