不要通过Executors类来创建线程池,一定要通过new ThreadPoolExecutor(…)来创建线程池。(参照阿里JAVA开发规范1.5泰山版)
先来介绍创建线程池涉及到的7个参数。
public ThreadPoolExecutor(int corePoolSize, //核心线程数
int maximumPoolSize, //最大线程数
long keepAliveTime, //保持时间
TimeUnit unit, //保持时间类型
BlockingQueue<Runnable> workQueue, //任务队列
ThreadFactory threadFactory, //线程池工厂
RejectedExecutionHandler handler //拒绝策略)
我们一一来解释
核心线程数 和 最大线程数
线程池中的线程分为两种,一种为核心线程(Daemon),一种是普通线程。核心线程是我们线程池启动后最少要维护的线程(这里指的是一旦新增任务,核心线程全部启动后),当核心线程都在执行任务的时候,新的任务又来了,那么任务放入队列中,并且新增普通线程来处理。普通线程数最多为 MAX-CORE。
keepAliveTime 和 unit
当普通线程在keepAliveTime个时间单位unit后没有任务执行,那么线程池主动释放掉普通线程,归还给操作系统。
workQueue
任务队列
1.SynchronousQueue
队列长度为0,有新的任务必须消费否则阻塞。
2.ArrayBlockingQueue
有界队列
3.LinkedBlockingDeque
“无界队列” (Integer.MAX_VALUE)
等类型。
threadFactory
线程工厂,可以自定义,不指定的话默认defalut。(建议实际环境中自定义)
RejectedExecutionHandler
拒绝策略,一般用不上,时间环境需要自定义。
根据打印信息观察线程池内部任务队列和线程的信息。
int MaxCPU = Runtime.getRuntime().availableProcessors();
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(MaxCPU
,MaxCPU
,60
,TimeUnit.SECONDS
, new LinkedBlockingQueue()
);
for(int i=0; i<3; i++){
threadPoolExecutor.execute(() -> {
try {
Thread.sleep(8000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(threadPoolExecutor.toString());
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
java.util.concurrent.ThreadPoolExecutor@44e81672[Running, pool size = 3, active threads = 3, queued tasks = 0, completed tasks = 0]