public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
int c = ctl.get();
//1.核心线程没有达到最大值,则创建核心线程
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
//2.线程池正在运行,切阻塞队列可以加入任务
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);
}
//3.创建非核心线程执行任务
else if (!addWorker(command, false))
//创建非核心线程失败,执行拒绝策略
reject(command);
}
主要步骤:
1.核心线程没有达到最大值,则创建核心线程
2.线程池正在运行,切阻塞队列可以加入任务
3.创建非核心线程执行任务
4.执行拒绝策略
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
//自旋,如果添加失败返回false
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// 线程池大于shutdown或者是shutdown切阻塞队列是空的时候
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) {
//可冲入所,保证work添加到workers中不会有线程问题
//workers为HashSet,并不是线程安全的
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) {
t.start();
workerStarted = true;
}
}
} finally {
//失败,移除添加的worker,线程数量减少
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
private void addWorkerFailed(Worker w) {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
if (w != null)
workers.remove(w);
decrementWorkerCount();
//关闭线程池
tryTerminate();
} finally {
mainLock.unlock();
}
}
其中new work需要特殊关注
//创建线程
w = new Worker(firstTask);
private final class Worker extends AbstractQueuedSynchronizer implements Runnable{
Worker(Runnable firstTask) {
setState(-1); // inhibit interrupts until runWorker
this.firstTask = firstTask;
//注意:将自己传给线程,线程启动时,启动的就是自己
this.thread = getThreadFactory().newThread(this);
}
public void run() {
runWorker(this);
}
......
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阻塞从队列中拿到需要执行的任务
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);
}
}
......
//从阻塞队列中去拿去任务
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 {
Runnable r = timed ?
//阻塞定时后返回null
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
//一直阻塞
workQueue.take();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}