版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
/**
* Attempts to stop all actively executing tasks, halts the
* processing of waiting tasks, and returns a list of the tasks
* that were awaiting execution. These tasks are drained (removed)
* from the task queue upon return from this method.
* 尝试停止所有正在执行的任务,终止等待中的任务,并且返回一个等待执行的任务的list。
* 当此方法返回时,将从任务队列中删除这些任务
* <p>This method does not wait for actively executing tasks to
* terminate. Use {@link #awaitTermination awaitTermination} to
* do that.
* 此方法不会等待正在执行的任务停止,要达到此效果,需使用awaitTermination
* <p>There are no guarantees beyond best-effort attempts to stop
* processing actively executing tasks. This implementation
* cancels tasks via {@link Thread#interrupt}, so any task that
* fails to respond to interrupts may never terminate.
* 此方法只是尽力尝试终止正在执行的任务,并不保证一定能终止。
* 是通过 Thread#interrupt方法来完成取消任务,因此任何不响应中断的任务可能永远不会终止运行
* @throws SecurityException {@inheritDoc}
*/
public List<Runnable> shutdownNow() {
List<Runnable> tasks;
final ReentrantLock mainLock = this.mainLock;
//获得独占锁
mainLock.lock();
try {
//检查关闭权限
checkShutdownAccess();
//无线循环尝试将线程池状态置为STOP
advanceRunState(STOP);
//中断已开始执行的线程
interruptWorkers();
tasks = drainQueue();
} finally {
mainLock.unlock();
}
tryTerminate();
return tasks;
}
advanceRunState在 shutdown分析过
private void advanceRunState(int targetState) {
for (;;) {
int c = ctl.get();
if (runStateAtLeast(c, targetState) ||
ctl.compareAndSet(c, ctlOf(targetState, workerCountOf(c))))
break;
}
}
/**
* Interrupts all threads, even if active. Ignores SecurityExceptions
* (in which case some threads may remain uninterrupted).
* 中断所有线程,即使是活跃的线程。
* 忽略安全异常(在这种情况下有些线程可能仍然没有没终止)
*/
private final class Worker
extends AbstractQueuedSynchronizer
implements Runnable
{
private void interruptWorkers() {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
for (Worker w : workers)
w.interruptIfStarted();
} finally {
mainLock.unlock();
}
}
void interruptIfStarted() {
Thread t;
/aqs里面的state为-1时表示线程还未为执行,会忽略中断操作,因此这里先判断下state>=0
if (getState() >= 0 && (t = thread) != null && !t.isInterrupted()) {
try {
t.interrupt();
} catch (SecurityException ignore) {
}
}
}
}
/**
* Drains the task queue into a new list, normally using
* drainTo. But if the queue is a DelayQueue or any other kind of
* queue for which poll or drainTo may fail to remove some
* elements, it deletes them one by one.
* 将任务队列里面的任务导入到一个新的list,正常情况下应该用BlockingQueue的drainTo方法。
* 但如果queue是一个延时队列或其他某些类型的队列用poll 或者 drainTo方法可能不能移除某些元素,这时候就用循环一个一个移除。
*/
private List<Runnable> drainQueue() {
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;
}