execute方法
//将Runnable类型的任务提交到线程池中
public void execute(Runnable command) {
//如果任务为null 则抛出异常
if (command == null)
throw new NullPointerException();
//获取线程池的状态和线程数量
int c = ctl.get();
//如果线程数量小于核心线程数
if (workerCountOf(c) < corePoolSize) {
//则开启新的线程执行任务
if (addWorker(command, true))
return;
c = ctl.get();
}
//如果线程池处于Running状态,并且线程数量大于核心线程数,则将任务添加到阻塞队列中
if (isRunning(c) && workQueue.offer(command)) {
//再次获取线程池状态和线程数量
int recheck = ctl.get();
//如果线程池状态不是Running 则从队列中移除任务
if (! isRunning(recheck) && remove(command))
//同时执行拒绝策略
reject(command);
//如果线程池中没有线程
else if (workerCountOf(recheck) == 0)
//则向线程池中添加一条线程
addWorker(null, false);
}
//队列已满,添加任务失败
else if (!addWorker(command, false))
//则执行拒绝策略
reject(command);
}
addWorker方法
//添加任务
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;
//下面循环的主要作用为通过CAS方式增加线程的个数
for (;;) {
//获取线程池中的线程数量
int wc = workerCountOf(c);
//如果线程池中的线程数量超出限制,直接返回false
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
//通过CAS方式向线程池新增线程数量
if (compareAndIncrementWorkerCount(c))
//通过CAS方式保证只有一个线程执行成功,跳出最外层循环
break retry;
//重新获取ctl的值
c = ctl.get(); // Re-read ctl
//如果CAS操作失败了,则需要在内循环中重新尝试通过CAS新增线程数量
if (runStateOf(c) != rs)
continue retry;
// else CAS failed due to workerCount change; retry inner loop
}
}
//跳出最外层for循环,说明通过CAS新增线程数量成功
//此时创建新的工作线程
boolean workerStarted = false;
boolean workerAdded = false;
Worker w = null;
try {
//将执行的任务封装成worker
w = new Worker(firstTask);
final Thread t = w.thread;
if (t != null) {
//独占锁,保证操作workers时的同步
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
//此处需要重新检查线程池状态
//原因是在获得锁之前可能其他的线程改变了线程池的状态
int rs = runStateOf(ctl.get());
if (rs < SHUTDOWN ||
(rs == SHUTDOWN && firstTask == null)) {
if (t.isAlive()) // precheck that t is startable
throw new IllegalThreadStateException();
//向worker中添加新任务
workers.add(w);
int s = workers.size();
if (s > largestPoolSize)
largestPoolSize = s;
//将是否添加了新任务的标识设置为true
workerAdded = true;
}
} finally {
//释放独占锁
mainLock.unlock();
}
//添加新任成功,则启动线程执行任务
if (workerAdded) {
t.start();
//将任务是否已经启动的标识设置为true
workerStarted = true;
}
}
} finally {
//如果任务未启动或启动失败,则调用addWorkerFailed(Worker)方法
if (! workerStarted)
addWorkerFailed(w);
}
//返回是否启动任务的标识
return workerStarted;
}
shutdown方法
public void shutdown() {
final ReentrantLock mainLock = this.mainLock;
//获取线程池全局锁
mainLock.lock();
try {
//检查是否有关闭线程池得权限
checkShutdownAccess();
//将当前线程池状态置为SHUTDOWN状态
advanceRunState(SHUTDOWN);
//中断Worker线程
interruptIdleWorkers();
//为ScheduledThreadPoolExecutor调用得钩子函数
onShutdown(); // hook for ScheduledThreadPoolExecutor
} finally {
//是否线程池全局锁
mainLock.unlock();
}
//尝试将状态变为TERMINATED
tryTerminate();
}
shutdownNow方法
public List<Runnable> shutdownNow() {
List<Runnable> tasks;
final ReentrantLock mainLock = this.mainLock;
//获取全局锁
mainLock.lock();
try {
//检查是否有关闭线程池得权限
checkShutdownAccess();
//将线程池状态置为STOP
advanceRunState(STOP);
//中断Worker线程
interruptWorkers();
//获取被中断得线程
tasks = drainQueue();
} finally {
//释放全局锁
mainLock.unlock();
}
//尝试将状态置为TERMINATED
tryTerminate();
return tasks;
}
awaitTermination方法
public boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException {
//获取距离超时时间得剩余时长
long nanos = unit.toNanos(timeout);
final ReentrantLock mainLock = this.mainLock;
//获取全局锁
mainLock.lock();
try {
//自旋
for (;;) {
//如果当前线程池状态为TERMINATED,则返回true
if (runStateAtLeast(ctl.get(), TERMINATED))
return true;
//到达超时时间,返回false
if (nanos <= 0)
return false;
//重置距离超时时间得剩余时长
nanos = termination.awaitNanos(nanos);
}
} finally {
//释放全局锁
mainLock.unlock();
}
}