ThreadPoolExecutor 的 shutdown() 和shutdownNow()

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;
}

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");
//}
}
}


}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值