1.shutdown方法
//不会接收新任务,但会继续处理队列中的任务
public void shutdown() {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
//校验权限(如果没有声明或者配置SecurityManager,是会通过的)
checkShutdownAccess();
//线程池状态设置为SHUTDOWN状态,
advanceRunState(SHUTDOWN);
//interrupt 空闲工作线程
interruptIdleWorkers();
onShutdown(); // hook for ScheduledThreadPoolExecutor
} finally {
mainLock.unlock();
}
tryTerminate();
}
interruptIdleWorkers方法
private void interruptIdleWorkers(boolean onlyOne) {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
for (Worker w : workers) {
Thread t = w.thread;
//w.tryLock(),尝试获取锁(如果能获取到,说明没有在执行任务,可中断)
//在runWorker w.lock和w.unlock之间的不会中断
if (!t.isInterrupted() && w.tryLock()) {
try {
t.interrupt();
} catch (SecurityException ignore) {
} finally {
w.unlock();
}
}
if (onlyOne)
break;
}
} finally {
mainLock.unlock();
}
}
2.shutdownNow方法
//不接受新任务,不处理队列中的任务,并中断正在进行的任务(中断线程,但当前任务会继续执行完在结束)
public List<Runnable> shutdownNow() {
List<Runnable> tasks;
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
//检查是否有权限关闭线程池,和中断工作线程
checkShutdownAccess();
//线程池状态设置为STOP状态,
advanceRunState(STOP);
//interrupt所有已经启动(start())的工作线程(runWorker->w.unlock()之后)
interruptWorkers();
//清空队列中的任务,并返回未处理的任务
tasks = drainQueue();
} finally {
mainLock.unlock();
}
//尝试终止线程池
tryTerminate();
return tasks;
}
interruptIfStarted
shutdownNow-> interruptWorkers-> interruptIfStarted,
//中断已经执行runworker的工作线程
void interruptIfStarted() {
Thread t;
//w.unlock:state=0;w.lock:state=1,在执行到runWorker,w.unlock时就可以中断了
if (getState() >= 0 && (t = thread) != null && !t.isInterrupted()) {
try {
t.interrupt();
} catch (SecurityException ignore) {
}
}
}
3.awaitTermination
这个不是关闭方法,是可阻塞等待线程池关闭的方法
//1:在超时(timeout)后仍未结束,返回false
//2: 在线程池终止时,会返回true
public boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException {
//以纳秒为单位,阻塞的最大时间,超过这个时间,如果线程池还没终止,返回false
long nanos = unit.toNanos(timeout);
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
for (;;) {
//如果线程池已经终止了。返回true
if (runStateAtLeast(ctl.get(), TERMINATED))
return true;
//如果超时了,返回false
if (nanos <= 0)
return false;
//阻塞方法,直到时间超过nanos或者通过tryTerminate()->termination.signalAll();唤醒
nanos = termination.awaitNanos(nanos);
}
} finally {
mainLock.unlock();
}
}