线程池概述
线程池(Thread Pool)是一种基于池化思想管理线程的工具。使用线程池可以带来诸多好处:
①降低资源消耗:通过池化技术复用已创建的线程,减少线程创建和销毁的损耗。
②提高响应速度:任务到达时,特定情况下无需再创建线程。
③便于管理。
java中线程池相关的接口和类主要包括:
Executor是线程执行器
Runnable接口定义任务逻辑,通过这两个接口将任务的定义和执行分离开来。
ThreadPoolExecutor实现ExecutorService,以内部线程池的形式对外提供管理任务执行,线程调度,线程池管理等服务
Executors中提供了一些默认提供的线程池,都是通过参数设置来实现不同的线程池机制
线程池的七个参数
核心构造方法:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.acc = System.getSecurityManager() == null ?
null :
AccessController.getContext();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
corePoolSize: 核心线程数
maximumPoolSize:最大线程数
keepAliveTime:核心线程除外的空闲线程存活的最大时间,之后归还给OS
unit:keepAliveTime的单位
workQueue:阻塞任务队列
threadFactory:新建线程工厂
handler:拒绝策略,jdk默认提供四种,但是生产环境一般需要自定义实现
下面通过任务调度execute方法研究下参数间的关系
public void execute(Runnable command) {
if (command == null)
throw new