---
title: "ThreadPoolExecutor 的 shutdown（） 和shutdownNow（）"
author: "alphafox"
date: "2013-03-04T10:23:00Z"
tags: []
slug: "threadpoolexecutor-shutdown-shutdownnow"
draft: false
lastmod: "2013-03-27T21:18:30Z"
id: 1837620
url: "https://alphafox.iteye.com/blog/1837620"
---

public List&lt;Runnable&gt; shutdownNow() {  
List&lt;Runnable&gt; tasks;  
final ReentrantLock mainLock = this.mainLock;  
mainLock.lock();  
try {  
checkShutdownAccess();  
advanceRunState(STOP);  
interruptWorkers();  
tasks = drainQueue();  
} finally {  
mainLock.unlock();  
}  
tryTerminate();  
return tasks;  
}

public void shutdown() {  
final ReentrantLock mainLock = this.mainLock;  
mainLock.lock();  
try {  
checkShutdownAccess();  
advanceRunState(SHUTDOWN);  
interruptIdleWorkers();  
onShutdown(); // hook for ScheduledThreadPoolExecutor  
} finally {  
mainLock.unlock();  
}  
tryTerminate();  
}

对比其代码可知 shutdown 只是将空闲的线程interrupt() 了， 因此在shutdown（）之前提交的任务可以继续执行直到结束。

而shutdownNow 是interrupt所有线程， 因此大部分线程将立刻被中断。之所以是大部分，而不是全部 ，是因为interrupt()方法能力有限。

如果线程中没有sleep 、wait、Condition、定时锁等应用, interrupt()方法是无法中断当前的线程的。所以，ShutdownNow()并不代表线程池就一定立即就能退出，它可能必须要等待所有正在执行的任务都执行完成了才能退出。

例如下面这种情况 将一直打印 go to sleep

package edu.neu.xiaobing.concurrent;

import java.util.concurrent.ExecutorService;  
import java.util.concurrent.Executors;

public class Interrupt {

/\**  
\* @param args  
\*/  
public static void main(String\[] args) {  
// TODO Auto-generated method stub

ExecutorService executor = Executors.newCachedThreadPool();  
executor.execute(new Interrupt().new MyRunnable());  
executor.shutdownNow();  
}

class MyRunnable implements Runnable{

@Override  
public void run() {  
// TODO Auto-generated method stub  
while(true){  
System.out.println("go to sleep");  
//try {  
//  
//Thread.sleep(100000);  
//  
//} catch (InterruptedException e) {  
//// TODO Auto-generated catch block  
//e.printStackTrace();  
//System.out.println("sleeping");  
//}  
}  
}

}

}