execute:
getTask:
execute方法时暴露给开发者提交任务的方法,这个方法就是整个线程池的入口。当然还有submit类方法,实际上也是调用了execute方法。
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) { // 当前worker数量少于corePoolSize,直接开启一个核心线程执行
if (addWorker(command, true)) // 添加核心线程失败
return;
c = ctl.get();
}
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);
}
addWorker:
添加工作线程方法,这个方法时ThreadPoolExecutor的核心方法,代码中包含了多处状态检测。添加成功后则运行线程执行任务。
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 {
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();
workers.add(w); // 保存新建的工作线程
int s = workers.size();
if (s > largestPoolSize)
largestPoolSize = s;
workerAdded = true;
}
} finally {
mainLock.unlock();
}
if (workerAdded) { // 新建工作线程添加成功后,调用start方法,执行任务
t.start();
workerStarted = true;
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
Worker:
private final class Worker
extends AbstractQueuedSynchronizer
implements Runnable
{
final Thread thread; // 工作线程
Runnable firstTask; // 线程执行的任务,可能为null
volatile long completedTasks; // 已经完成的任务
Worker(Runnable firstTask) {
setState(-1);
this.firstTask = firstTask;
this.thread = getThreadFactory().newThread(this); // 新建线程
}
public void run() {
runWorker(this); // 线程执行runWorker()方法
}
// AQS实现锁的一些方法,lock、unlock,用于锁定Worker同时只能有一个线程访问
}
runWorker是每个工作线程真正执行的方法,该方法参数Worker中包含了线程本身和要执行的任务。注意此方法是在各个工作线程中调用的。各个线程能够主动从任务队列中获取任务来执行。
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
// 首次while循环前,task不为null,则是根据某个任务构建的Worker,task为null,
// 则是构建Worker时,只是为了开启一个线程,指定了firstTask为null
while (task != null || (task = getTask()) != null) { // 若task为null,当前线程主动从任务队列中获取任务,有可能发生超时
w.lock();
if ((runStateAtLeast(ctl.get(), STOP) ||
(Thread.interrupted() &&
runStateAtLeast(ctl.get(), STOP))) &&
!wt.isInterrupted())
wt.interrupt();
try {
beforeExecute(wt, task); // 钩子方法(protected),ThreadPoolExecutor中为空方法
Throwable thrown = null;
try {
task.run(); // 直接在工作线程中调用任务的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); // 钩子方法(protected),ThreadPoolExecutor中为空方法
}
} finally {
task = null; // 令task为null,下次循环时,线程主动队列中获取任务
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
processWorkerExit(w, completedAbruptly);
}
}
getTask:
是各个线程通过此方法从队列中获取任务,非核心线程有超时策略。此方法也是在各个线程中调用。此方法返回null时,runWorker中while循环结束,线程运行终止。
private Runnable getTask() {
boolean timedOut = false;
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
decrementWorkerCount();
return null;
}
int wc = workerCountOf(c);
// allowCoreThreadTimeOut用来表示是否核心线程也开启超时策略,默认为fallse
// 如果为true,则所有线程均会发生超时,就不存在核心线程一说了。
// 可以通过set方法设置allowCoreThreadTimeOut
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount(c))
return null;
continue;
}
try {
// poll会发声超时,而take会一直阻塞,这也就是为什么核心线程即使在没有任务执行时,
// 也不会终止(一直阻塞在take方法),而非核心线程超时后就会终止。
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}