ThreadPoolExecutor构造函数中最核心的有五个参数corePoolSize(核心线程池),maximumPoolSize(最大线程池),keepAliveTime(非核心线程池存活时间),TimeUnit (非核心线程池存活时间单位),workQueue(任务队列)
1.当前运行的线程数量小于corePoolSize核心线程池时,创建一个核心线程执行该任务
2.当前运行的线程数量大于或等于corePoolSize并且小于任务队列的最大值时,将任务加入到任务队列中等待核心线程执行完任务后从任务队列中获取任务再执行,任务队列将任务出队。
3.当任务队列已满时并且corePollSize
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
this(corePoolSize,
keepAliveTime,
unit,
workQueue,
Executors.defaultThreadFactory(),
defaultHandler);
}
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
threadFactory, defaultHandler);
}
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
RejectedExecutionHandler handler) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), handler);
}
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.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
/**
*默认的DefaultThreadFactory
**/
static class DefaultThreadFactory implements ThreadFactory {
//AtomicInteger可以进行线程安全的递增或递减
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
DefaultThreadFactory() {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
namePrefix = "pool-" +
poolNumber.getAndIncrement() +
"-thread-";
}
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r,
namePrefix + threadNumber.getAndIncrement(),
0);
if (t.isDaemon())
t.setDaemon(false);
if (t.getPriority() != Thread.NORM_PRIORITY)
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
}
/**
*当提交任务数超过maxmumPoolSize+workQueue之和时,任务会交给 RejectedExecutionHandler来处理.默认的线程池使用的是AbortPolicy类来处理这种情况,从下面AbortPolicy类实现的rejectedExecution方法可以看出,默认的RejectedExecutionHandler并未处理任务超过maxmumPoolSize+workQueue之和的情况,而是抛出异常。
**/
public static class AbortPolicy implements RejectedExecutionHandler {
public AbortPolicy() { }
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
throw new RejectedExecutionException("Task " + r.toString() +
" rejected from " +
e.toString());
}
}
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
int c = ctl.get();
//判断当前运行的线程数是否小于核心线程池中线程数
if (workerCountOf(c) < corePoolSize) {
//添加线程到工作线程集中,并且工作线程的最大线程数必须小于核心线程池中的线程数
if (addWorker(command, true))
return;
c = ctl.get();
}
//当workerCountOf(c) >= corePoolSize时,把任务加入任务队列中
//判断线程池是否处于运行状态,且任务是否插入任务队列成功
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
//判断线程池是否处于运行状态,如果不是则使刚刚的任务出队
if (! isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
//当任务队列已满,加入任务队列失败,就新建一个线程放入线程池中。当提交任务数超过maxmumPoolSize+workQueue之和时添加任务失败。这时可以交给RejectedExecutionHandler来处理来处理。
else if (!addWorker(command, false))
reject(command);
}
private static final int CAPACITY = (1 << COUNT_BITS) – 1; //低29位表示最大线程数
//五种线程池状态
private static final int RUNNING = -1 << COUNT_BITS; //int型变量高3位(含符号位)101表RUNING
private static final int SHUTDOWN = 0 << COUNT_BITS; //高3位000
private static final int STOP = 1 << COUNT_BITS; //高3位001
private static final int TIDYING = 2 << COUNT_BITS; //高3位010
private static final int TERMINATED = 3 << COUNT_BITS; //高3位011
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {
int c = ctl.get();
//获取线程池的状态
int rs = runStateOf(c);
//检查线程池是否处于运行状态,核心线程池中是否还有空闲线程
if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
return false;
for (;;) {
//获取当前正在运行线程数
int wc = workerCountOf(c);
//当前运行的线程数不能大于线程池的最大容量或者(core为true时不能大于核心线程池容量,core为false时不能大于最大线程池容量)
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
//将正在运行的线程数+1,数量自增成功则跳出循环
if (compareAndIncrementWorkerCount(c))
break retry;
c = ctl.get();
if (runStateOf(c) != rs)
continue retry;
}
}
boolean workerStarted = false;
boolean workerAdded = false;
Worker w = null;
try {
//将任务封装到工作线程中
w = new Worker(firstTask);
final Thread t = w.thread;
if (t != null) {
final ReentrantLock mainLock = this.mainLock;
//获取全局锁
mainLock.lock();
try {
//再次查看线程池的运行状态
int rs = runStateOf(ctl.get());
//线程池处于运行状态,或者线程池关闭且任务线程为空
if (rs < SHUTDOWN ||
(rs == SHUTDOWN && firstTask == null)) {
//线程处于活跃状态时抛出异常,正常情况该线程还未执行
if (t.isAlive())
throw new IllegalThreadStateException();
//将新创建的工作线程加入的工作线程集中
workers.add(w);
//获取工作线程集的实际大小
int s = workers.size();
//更新工作线程集的原有大小
if (s > largestPoolSize)
largestPoolSize = s;
//设置状态为添加工作线程成功
workerAdded = true;
}
} finally {
//是否全局锁
mainLock.unlock();
}
if (workerAdded) {
//如果工作线程添加成功,启动工作线程
t.start();
//设置工作线程为启动状态
workerStarted = true;
}
}
} finally {
if (! workerStarted)
//如果创建或启动工作线程失败,就从工作线程集中移除该工作线程
addWorkerFailed(w);
}
return workerStarted;
}