线程池的创建可以使用Executors类中的方法创建,可以参考常用的四种线程池的创建,下面来看J.U.C包下的ThreadPoolExecutor,此类主要有以下构造方法:
/**第一种创建方式*/
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
/**第二章创建方式*/
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue workQueue,
RejectedExecutionHandler handler) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), handler);
}
/**第三种创建方式*/
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue workQueue,
ThreadFactory threadFactory) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
threadFactory, defaultHandler);
}
/**第四种创建方式*/
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue 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.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
corePoolSize:核心线程池的大小,线程池创建完成之后,线程池中默认没有任何线程。只有在有任务到达时才会创建一个线程去执行,直到corePoolSize。
maximumPoolSize:线程池中允许最大的线程数。
keepAliveTime:空闲线程等待新任务的最大存活时间。
unit:keepAliveTime的时间单位,比如TimeUnit.MILLISECONDS;TimeUnit.SECONDS; TimeUnit.MINUTES; TimeUnit.HOURS;
workQueue:阻塞队列,当线程池中的线程大于corePoolSize时,新建的任务将会进入阻塞队列等待执行,可以查看常用的阻塞队列。
threadFactory:创建线程的工厂
handler:拒绝任务的处理策略。
状态转换:
RUNNING -> SHUTDOWN: 在调用shutDown()方法时。
(RUNNING or SHUTDOWN) -> STOP:在调用shutDownNow()方法时。
SHUTDOWN -> TIDYING:线程池和阻塞队列都为空。
STOP -> TIDYING :线程池为空。
TIDYING -> TERMINATED :terminated()方法执行完毕时。