线程池状态
* RUNNING: Accept new tasks and process queued tasks //执行中
* SHUTDOWN: Don't accept new tasks, but process queued tasks //继续处理队列中的任务
* STOP: Don't accept new tasks, don't process queued tasks,
* and interrupt in-progress tasks //不接受任务,也不继续处理队列中的任务
* TIDYING: All tasks have terminated, workerCount is zero,
* the thread transitioning to state TIDYING//所有task都执行完的一个过渡阶段
* will run the terminated() hook method
* TERMINATED: terminated() has completed //结束
其中AtomicInteger变量ctl的功能非常强大:利用低29位表示线程池中线程数,通过高3位表示线程池的运行状态:
1、RUNNING:-1 << COUNT_BITS,即高3位为111,该状态的线程池会接收新任务,并处理阻塞队列中的任务;
//-1的二进制表示 11111111 11111111 11111111 11111111
2、SHUTDOWN: 0 << COUNT_BITS,即高3位为000,该状态的线程池不会接收新任务,但会处理阻塞队列中的任务;
3、STOP : 1 << COUNT_BITS,即高3位为001,该状态的线程不会接收新任务,也不会处理阻塞队列中的任务,而且会中断正在运行的任务;
//1在二进制中的表示:00000000 00000000 00000000 00000001
4、TIDYING : 2 << COUNT_BITS,即高3位为010;
5、TERMINATED: 3 << COUNT_BITS,即高3位为011;
一 入口
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
/*
* Proceed in 3 steps:
*
* 1. If fewer than corePoolSize threads are running, try to
* start a new thread with the given command as its first
* task. The call to addWorker atomically checks runState and
* workerCount, and so prevents false alarms that would add
* threads when it shouldn't, by returning false.
*
* 2. If a task can be successfully queued, then we still need
* to double-check whether we should have added a thread
* (because existing ones died since last checking) or that
* the pool shut down since entry into this method. So we
* recheck state and if necessary roll back the enqueuing if
* stopped, or start a new thread if there are none.
*
* 3. If we cannot queue task, then we try to add a new
* thread. If it fails, we know we are shut down or saturated
* and so reject the task.
*/
int c = ctl.get();
//小于核心线程数是,新增一个工作线程
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
// workQueue.offer(command)将执行参数添加到阻塞队列中,
//如果满,则返回false,这里是任务进入阻挡队列的唯一入口
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);
}
//走到这里说明,核心线程数达到上限,且阻塞队列已经满了,创建非核心线程帮助处理任务
else if (!addWorker(command, false))
reject(command);
}
二 workThread添加过程
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
//校验线程池的运行状态,是否允许继续添加工作线程
if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
return false;
for (;;) {
int wc = workerCountOf(c);
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
if (compareAndIncrementWorkerCount(c))
break retry;
c = ctl.get(); // Re-read ctl
if (runStateOf(c) != rs)
continue retry;
// else CAS failed due to workerCount change; retry inner loop
}
}
boolean workerStarted = false;
boolean workerAdded = false;
Worker w = null;
try {
//新增工作线程,Worker继承AQS和Runable,firstTask执行参数
w = new Worker(firstTask);
final Thread t = w.thread;
if (t != null) {
//在加锁的条件下进行
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
// Recheck while holding lock.
// Back out on ThreadFactory failure or if
// shut down before lock acquired.
int rs = runStateOf(ctl.get());
//上面线程池执行状态的判断是在无锁模式下,这里在有锁模式下,再次判断线程池
//执行状态
if (rs < SHUTDOWN ||
(rs == SHUTDOWN && firstTask == null)) {
if (t.isAlive()) // precheck that t is startable
throw new IllegalThreadStateException();
//将新增工作线程添加的set集合中
workers.add(w);
int s = workers.size();
if (s > largestPoolSize)
largestPoolSize = s;
workerAdded = true;
}
} finally {
mainLock.unlock();
}
if (workerAdded) {
//执行work工作线程,这里会启动work线程的run()方法,从阻塞队列中去任务,执
//行,接下来的工作都由run()方法发起,处理,核心线程超时管理,非核心线程超
//时管理,worker工程线程的删除,从阻塞队列不断去任务执行,都由run()中的逻
//辑处理
t.start();
workerStarted = true;
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
三 worker的run()方法
public void run() {
runWorker(this);
}
四 runWorker()
//是一个final方法
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
//这个循环保证当前工作线程一直从队里中取任务执行
//结束这个循环表示,有一个工作线程需要被回收
//一个工作线程是否会被销毁,控制逻辑放在getTask()方法里面
//如果getTask()返回null表无任务需要执行,则当前工作线程将被销毁
//如果当前工作线程数<=核心线程数,则在从阻塞队列中取任务时
//workQueue.take() 当队列不为空时返回,移除并返回头部元素,否则阻塞
//这里通过阻塞的方法保证核心线程不被销毁
while (task != null || (task = getTask()) != null) {
w.lock();
// If pool is stopping, ensure thread is interrupted;
// if not, ensure thread is not interrupted. This
// requires a recheck in second case to deal with
// shutdownNow race while clearing interrupt
if ((runStateAtLeast(ctl.get(), STOP) ||
(Thread.interrupted() &&
runStateAtLeast(ctl.get(), STOP))) &&
!wt.isInterrupted())
wt.interrupt();
try {
beforeExecute(wt, task);
Throwable thrown = null;
try {
//执行目前参数方法
task.run();
} catch (RuntimeException x) {
thrown = x; throw x;
} catch (Error x) {
thrown = x; throw x;
} catch (Throwable x) {
thrown = x; throw new Error(x);
} finally {
afterExecute(task, thrown);
}
} finally {
task = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
//销毁当前worker
processWorkerExit(w, completedAbruptly);
}
}
五 getTask()方法
private Runnable getTask() {
boolean timedOut = false; // Did the last poll() time out?
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
decrementWorkerCount();
return null;
}
int wc = workerCountOf(c);
//判断核心线程是否受空闲销毁控制
// Are workers subject to culling?
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount(c))
return null;
continue;
}
try {
//如果timed=true表示有空闲等待时长限制
//keepAliveTime创建线程池传入得时间值
//workQueue.take() 当队列不为空时返回,移除并返回头部元素,否则阻塞
//这里通过阻塞的方法保证核心线程不被销毁
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}