public List<Runnable> shutdownNow() {
List<Runnable> tasks;
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
checkShutdownAccess();
advanceRunState(STOP);
interruptWorkers();
tasks = drainQueue();
} finally {
mainLock.unlock();
}
tryTerminate();
return tasks;
}
shutdownNow 是interrupt所有线程, 因此大部分线程将立刻被中断。之所以是大部分,而不是全部 ,是因为interrupt()方法能力有限。
如果线程中没有sleep 、wait、Condition、定时锁等应用, interrupt()方法是无法中断当前的线程的。所以,ShutdownNow()并不代表线程池就一定立即就能退出,它可能必须要等待所有正在执行的任务都执行完成了才能退出。
long t1 = System.currentTimeMillis();
ExecutorService singleThread = newSingleThreadExecutor().execute(() -> {
try {
while (true) {
long t2 = System.currentTimeMillis();
if ((t2 - t1 > timeout * 1000) && timeout > 0) {
//timeout
break;
}
// do something
Thread.sleep(10);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
new MaterialDialog.Builder(this)
.content("waiting...")
.contentGravity(GravityEnum.CENTER)
.cancelListener((dialog) -> {
singleThread.shutdownNow();
dialog.dismiss();
})
.show();