1. 常量和变量

private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0)); // 高3位为线程池的运行状态,低29位为当前线程总数

private static final int COUNT_BITS = Integer.SIZE - 3; // 32 -3 = 29
private static final int CAPACITY = (1 << COUNT_BITS) - 1; // 线程池容量:2^29 - 1(0001,1111,1111,1111,1111,1111,1111,1111)
private static final int RUNNING = -1 << COUNT_BITS; // 1110,0000,0000,0000,0000,0000,0000,0000
private static final int SHUTDOWN = 0 << COUNT_BITS; // 0000,0000,0000,0000,0000,0000,0000,0000
private static final int STOP = 1 << COUNT_BITS; // 0010,0000,0000,0000,0000,0000,0000,0000
private static final int TIDYING = 2 << COUNT_BITS; // 0100,0000,0000,0000,0000,0000,0000,0000
private static final int TERMINATED = 3 << COUNT_BITS; // 0110,0000,0000,0000,0000,0000,0000,0000
// RUNNING < SHUTDOWN < STOP < TIDYING < TERMINATED
// 1. 调用shutdown方法:RUNNING -> SHUTDOWN -> 中断workers中所有空闲的工作线程(getTask中)
// 立刻调用tryTerminate方法:SHUTDOWN -> TIDYING -> TERMINATED,若workQueue不为空,则线程池运行状态保持为SHUTDOWN
// 执行完workQueue中最后一个工作任务的工作线程在processWorkerExit中将调用tryTerminate方法:SHUTDOWN -> TIDYING -> TERMINATED
// 2. 调用shutdownNow方法:RUNNING || SHUTDOWN -> STOP -> 中断workers中所有已经启动的工作线程,获取和清空workQueue中所有尚未执行的工作任务
// 立刻调用tryTerminate方法:STOP -> TIDYING -> TERMINATED private static int ctlOf(int rs, int wc) { return rs | wc; }
private static int runStateOf(int c) { return c & ~CAPACITY; } // 取线程池的运行状态(ctl高3位)
private static int workerCountOf(int c) { return c & CAPACITY; } // 取当前线程总数(ctl低29位)
private static boolean isRunning(int c) { return c < SHUTDOWN; }
private static boolean runStateLessThan(int c, int s) { return c < s; }
private static boolean runStateAtLeast(int c, int s) { return c >= s; }
private boolean compareAndIncrementWorkerCount(int expect) { return ctl.compareAndSet(expect, expect + 1); }
private boolean compareAndDecrementWorkerCount(int expect) { return ctl.compareAndSet(expect, expect - 1); }
private void decrementWorkerCount() {
do {} while (! compareAndDecrementWorkerCount(ctl.get()));
} private final ReentrantLock mainLock = new ReentrantLock(); // workers锁
private final Condition termination = mainLock.newCondition(); // 等待线程池的运行状态成为TERMINATED(见awaitTermination方法)
private final HashSet<Worker> workers = new HashSet<Worker>(); // 工作线程集合
private final BlockingQueue<Runnable> workQueue; // 工作任务队列
private volatile int corePoolSize; // 最大核心线程数
private volatile int maximumPoolSize; // 最大线程数
private volatile long keepAliveTime; // 存活时间(空闲核心线程 && 空闲非核心线程)
private volatile ThreadFactory threadFactory; // 线程工厂
private volatile RejectedExecutionHandler handler; // 默认为defaultHandler
private volatile boolean allowCoreThreadTimeOut; // 允许空闲核心线程超时退出
private int largestPoolSize; // 线程总数的历史最大值
private long completedTaskCount; // 线程池执行的工作任务总数 private static final RejectedExecutionHandler defaultHandler = new AbortPolicy(); // 抛异常
private static final RuntimePermission shutdownPerm = new RuntimePermission("modifyThread");

2. 父类AbstractExecutorService

不详细讲AbstractExecutorService,将会涉及到FutrueTask类,有空大家可以研究下。

public abstract class AbstractExecutorService implements ExecutorService {
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
return new FutureTask<T>(runnable, value);
} protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
return new FutureTask<T>(callable);
} public Future<?> submit(Runnable task) {
if (task == null) throw new NullPointerException();
RunnableFuture<Void> ftask = newTaskFor(task, null); // FutureTask
execute(ftask);
return ftask;
} public <T> Future<T> submit(Runnable task, T result) {
if (task == null) throw new NullPointerException();
RunnableFuture<T> ftask = newTaskFor(task, result); // FutureTask
execute(ftask);
return ftask;
} public <T> Future<T> submit(Callable<T> task) {
if (task == null) throw new NullPointerException();
RunnableFuture<T> ftask = newTaskFor(task); // FutureTask
execute(ftask);
return ftask;
} ... ...
}

3. execute

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();
}
if (isRunning(c) && workQueue.offer(command)) { // 线程池正在运行 -> 在workQueue中添加工作任务
// 在workQueue中添加工作任务后需要确保两件事情
// 1. 线程池正在运行
// 2. 在允许空闲核心线程超时退出的情况下:当前线程总数 > 0
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command)) // 线程池正在关闭 -> 在workQueue中移除工作任务(command可能已被其它工作线程取走执行)
reject(command);
else if (workerCountOf(recheck) == 0) // corePoolSize == 0 || 所有核心工作线程超时(见getTask)
addWorker(null, false); // 补充一个非核心工作线程(未绑定工作任务):将在workQueue中取工作任务执行(command可能已被其它工作线程取走执行)
}
else if (!addWorker(command, false)) // 创建非核心工作线程:一定失败(线程池正在关闭) || 可能成功(未能在workQueue添加工作任务)
reject(command);
} private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {
// 线程池运行状态发生变化将回到此处
int c = ctl.get(); /*记录ctl*/
int rs = runStateOf(c);
// 线程池正在关闭 && (线程池运行状态 > SHUTDOWN || 工作任务不为空 || 工作任务队列为空)
// 线程池运行状态 > SHUTDOWN:STOP,不添加新的工作线程
// SHUTDOWN && 新的工作任务不为空:不执行新的工作任务,不添加新的工作线程
// SHUTDOWN && 工作任务队列为空:workQueue不存在待执行的工作任务,不添加新的工作线程
if (rs >= SHUTDOWN && ! (rs == SHUTDOWN && firstTask == null && ! workQueue.isEmpty()))
return false;
for (;;) {
// CAS(ctl)失败 && 线程池运行状态未发生变化:回到此处
int wc = workerCountOf(c);
// 当前线程总数 >= 线程池容量 || 当前线程数 > 核心线程数(最大线程数)
if (wc >= CAPACITY || wc >= (core ? corePoolSize : maximumPoolSize))
return false;
if (compareAndIncrementWorkerCount(c)) /*CAS设置ctl++*///当前工作线程总数++
break retry;
c = ctl.get();               /*重新记录ctl*/
if (runStateOf(c) != rs) // 线程池运行状态发生变化
continue retry;
}
}
boolean workerStarted = false;
boolean workerAdded = false;
Worker w = null;
try {
w = new Worker(firstTask); // firstTask可能为空
final Thread t = w.thread;
if (t != null) {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock(); // 加workers锁
try {
int rs = runStateOf(ctl.get());
// 线程池正在运行 || (线程池运行状态为SHUTDOWN && 工作任务为空 )
if (rs < SHUTDOWN || (rs == SHUTDOWN && firstTask == null)) {
if (t.isAlive())
throw new IllegalThreadStateException();
workers.add(w); // 添加工作线程到workers
int s = workers.size();
if (s > largestPoolSize) // 跟踪和记录线程总数的历史最大值
largestPoolSize = s;
workerAdded = true;
}
} finally {
mainLock.unlock(); // 释放workers锁
}
if (workerAdded) {
t.start(); // 启动工作线程
workerStarted = true; // 工作线程已启动
}
}
} finally {
if (! workerStarted) // 工作线程未启动
addWorkerFailed(w);
}
return workerStarted;
} private void addWorkerFailed(Worker w) {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock(); // 加workers锁
try {
if (w != null)
workers.remove(w); // 在workers中移除工作线程
decrementWorkerCount(); // 当前工作线程总数--
tryTerminate(); // 尝试终止线程池(w可能为shutdown后最后一个尚未运行而退出的工作线程,当前线程必须尝试终止线程池)
} finally {
mainLock.unlock(); // 释放workers锁
}
} public boolean remove(Runnable task) {
boolean removed = workQueue.remove(task); // 在workQueue中移除工作任务
tryTerminate(); // 尝试终止线程池(task可能为shutdown后workQueue中的最后一个工作任务,当前线程必须尝试终止线程池)
return removed;
} final void reject(Runnable command) {
handler.rejectedExecution(command, this); // 默认抛异常
}

4. ThreadPoolExecutor.Worker

不详细讲AbstractSynchronizer,有空大家可以研究下RenentranLock。

private final class Worker extends AbstractQueuedSynchronizer implements Runnable {
final Thread thread; // 实际线程
Runnable firstTask; // 首个工作任务(之后将为空)
volatile long completedTasks; // 执行的工作任务总数 Worker(Runnable firstTask) {
setState(-1); // state = -1 :加锁(未启动,不被中断)
this.firstTask = firstTask;
this.thread = getThreadFactory().newThread(this);
} public void run() {
runWorker(this); // 执行工作任务
} void interruptIfStarted() { // 中断已启动的工作线程
Thread t;
if (getState() >= 0 && (t = thread) != null && !t.isInterrupted()) {
try {
t.interrupt();
} catch (SecurityException ignore) {
}
}
} public void lock() { acquire(1); }
public boolean tryLock() { return tryAcquire(1); }
public void unlock() { release(1); } // 释放锁:state++(已启动,可被中断)

... ...
}

5. runWorker

final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // Worker.state++(已启动,允许中断)
boolean completedAbruptly = true;
try {
while (task != null || (task = getTask()) != null) { // 执行绑定的工作任务 || 执行workQueue中的工作任务
w.lock(); // 工作线程加锁
// 线程池运行状态 >= STOP || (getTask时被中断(清除中断位) && 线程池运行状态 >= STOP && 工作线程未再次被中断)
if ((runStateAtLeast(ctl.get(), STOP) || (Thread.interrupted() && runStateAtLeast(ctl.get(), STOP))) && !wt.isInterrupted())
wt.interrupt(); // 中断工作线程
try {
beforeExecute(wt, task); // noop
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); // noop
}
} finally {
task = null;
w.completedTasks++; // 跟踪和记录w执行过的工作任务总数
w.unlock(); // 工作线程释放锁
}
}
completedAbruptly = false; // 工作任务执行过程中未产生异常
} finally {
// 1. while正常退出(getTask == null):completedAbruptly为false
// 2. while非正常退出(工作任务执行过程中产生异常,如被中断):completedAbruptly为true
processWorkerExit(w, completedAbruptly);
}
} private Runnable getTask() {
boolean timedOut = false;
for (;;) {
// CAS(ctl)失败 || keepAliveTime内未取到工作任务 || 取工作任务时被中断:回到此处
int c = ctl.get(); /*记录ctl*/
int rs = runStateOf(c);
// 线程池运行状态 >= SHUTDOWN && (线程池运行状态 >= STOP || workQueue为空)
if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
decrementWorkerCount(); // 当前工作线程总数--
return null;
}
int wc = workerCountOf(c);
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize; // 核心线程允许超时 || 当前线程总数 > 最大核心线程数
if ((wc > maximumPoolSize || // 当前线程总数 > 最大线程数
(timed && timedOut)) && // (核心线程允许超时 && 线程已超时) || 当前线程总数 > 最大核心线程数
(wc > 1 || workQueue.isEmpty())) { // 当前线程总数 > 1 || workQueue为空
if (compareAndDecrementWorkerCount(c)) /*CAS设置ctl--*///当前工作线程总数--
return null;
continue;
}
try {
// 取工作任务(keepAliveTime内 || 永久等待)
Runnable r = timed ? workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) : workQueue.take();
if (r != null)
return r;
timedOut
= true; // 超时:keepAliveTime内未取到工作任务
} catch (InterruptedException retry) { // 取工作任务时被中断
timedOut = false; // 取工作任务时未超时
}
}
} protected void beforeExecute(Thread t, Runnable r) { }
protected void afterExecute(Runnable r, Throwable t) { } private void processWorkerExit(Worker w, boolean completedAbruptly) {
if (completedAbruptly) // 工作任务执行过程中产生异常,则当前工作线程总数--(超时则在getTask中已减少当前工作线程数)
decrementWorkerCount();
final ReentrantLock mainLock = this.mainLock;
mainLock.lock(); // 加workers锁
try {
completedTaskCount += w.completedTasks; // 跟踪和记录线程池执行过的工作任务总数
workers.remove(w); // 在workers中移除当前工作线程
} finally {
mainLock.unlock(); // 释放workers锁
}
tryTerminate(); // 尝试终止线程池(可能是shutdown后最后一个即将退出的工作线程)
int c = ctl.get();
if (runStateLessThan(c, STOP)) { // 线程池运行状态 < STOP
if (!completedAbruptly) { // 工作任务执行过程中未产生异常
int min = allowCoreThreadTimeOut ? 0 : corePoolSize;
if (min == 0 && ! workQueue.isEmpty()) // 最后一个超时退出的工作线程 && workQueue不为空
min = 1;
if (workerCountOf(c) >= min) // 当前线程总数 >= min
return;
}
addWorker(null, false); // 补充一个工作线程
}
}

6. shutdown和shutdownNow

public void shutdown() {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock(); // 加workers锁
try {
checkShutdownAccess();
advanceRunState(SHUTDOWN); // 若当前线程运行状态 < SHUTDOWN,则当前运行状态置为SHUTDOWN
interruptIdleWorkers(); // 中断所有空闲的工作线程
onShutdown(); // noop
} finally {
mainLock.unlock(); // 释放workers锁
}
tryTerminate(); // 尝试终止线程池
} private void advanceRunState(int targetState) {
for (;;) {
int c = ctl.get(); /*记录ctl*/
if (runStateAtLeast(c, targetState) || // 当前线程运行状态 >= targetState
ctl.compareAndSet(c, ctlOf(targetState, workerCountOf(c)))) /*CAS设置ctl = targetState*/
break;
}
} private void interruptIdleWorkers() {
interruptIdleWorkers(false); // 中断所有空闲的工作线程
} private void interruptIdleWorkers(boolean onlyOne) {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock(); // 加workers锁
try {
for (Worker w : workers) {
Thread t = w.thread;
if (!t.isInterrupted() && w.tryLock()) { // 工作线程未被中断 && 工作线程尝试加锁(正在执行的工作线程已加锁,见runWorker方法)
try {
t.interrupt(); // 中断工作线程
} catch (SecurityException ignore) {
} finally {
w.unlock(); // 工作线程释放锁
}
}
if (onlyOne) // 是否只中断一个?
break;
}
} finally {
mainLock.unlock(); // 释放workers锁
}
} void onShutdown() { } private static final boolean ONLY_ONE = true; final void tryTerminate() {
for (;;) {
// CAS(ctl)失败将回到此处
int c = ctl.get(); /*记录ctl*/// 线程池正在运行:当前线程不终止线程池
// 线程池运行状态 >= TIDYING:线程池即将终止,当前线程不终止线程池
// 线程运行状态为SHUTDOWN && workQueue不为空:正在等待workQueue为空,当前线程不终止线程池
if (isRunning(c) || runStateAtLeast(c, TIDYING) || (runStateOf(c) == SHUTDOWN && ! workQueue.isEmpty()))
return;
if (workerCountOf(c) != 0) {
// 之前未被shutdown方法中断的工作线程已执行完毕,在同步竞争workQueue中最后一个工作任务时阻塞
interruptIdleWorkers(ONLY_ONE); // 只中断一个空闲的工作线程
return;
}
final ReentrantLock mainLock = this.mainLock;
mainLock.lock(); // 加workers锁
try {
if (ctl.compareAndSet(c, ctlOf(TIDYING, 0))) { /*CAS设置ctl = TIDYING*/
try {
terminated(); // noop
} finally {
ctl.set(ctlOf(TERMINATED, 0)); // ctl = TERMINATED
termination.signalAll(); // 唤醒所有等待线程池结束的线程
}
return;
}
} finally {
mainLock.unlock(); // 释放workers锁
}
}
} protected void terminated() { }
// 可以在调用shutdown方法后调用awaitTermination方法等待线程池的运行状态成为TERMINATED,即等待最后一个执行线程退出
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
long nanos = unit.toNanos(timeout);
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
for (;;) {
if (runStateAtLeast(ctl.get(), TERMINATED))
return true;
if (nanos <= 0)
return false;
nanos = termination.awaitNanos(nanos);
}
} finally {
mainLock.unlock();
}
}
public List<Runnable> shutdownNow() { // 中断所有正在执行的工作线程,清空workers中空闲的工作线程
List<Runnable> tasks;
final ReentrantLock mainLock = this.mainLock;
mainLock.lock(); // 加workers锁
try {
checkShutdownAccess();
advanceRunState(STOP); // 若当前线程运行状态 < STOP,则当前运行状态置为STOP
interruptWorkers(); // 中断所有已经启动的工作线程(未启动的线程无法被中断)
tasks = drainQueue(); // 获取和清空workQueue中所有尚未执行的工作任务
} finally {
mainLock.unlock(); // 释放锁
}
tryTerminate(); // 尝试终止线程池(一定成功)
return tasks; // return 所有尚未执行的工作任务
} private void interruptWorkers() {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock(); // 加workers锁
try {
for (Worker w : workers)
w.interruptIfStarted(); // w已经启动则中断t
} finally {
mainLock.unlock(); // 加wrokers锁
}
} private List<Runnable> drainQueue() { // 获取和清空workQueue中所有尚未执行的工作任务
BlockingQueue<Runnable> q = workQueue;
ArrayList<Runnable> taskList = new ArrayList<Runnable>();
q.drainTo(taskList);
if (!q.isEmpty()) {
for (Runnable r : q.toArray(new Runnable[0])) {
if (q.remove(r))
taskList.add(r);
}
}
return taskList;
}
05-11 16:56