java shutdownnow,为什么ExecutorService.shutdownNow方法无法阻止线程

package util.concurrent;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.TimeUnit;

public class ShutdownDemo {

public static void main(String[] args) throws InterruptedException{

ExecutorService executor = Executors.newSingleThreadExecutor();

executor.execute(new Runnable(){

@Override

public void run() {

while(true){

System.out.println("-- test --");

}

}

});

TimeUnit.SECONDS.sleep(3);

executor.shutdownNow();

}

}

I have already invoked the shutdownNow method, why console continue to print "-- test --" ??

解决方案

Check out Thread.stop() in JavaDoc for the full reason:

Essentially, your thread must stop on it's own in order for your program to stay safe. Just stopping a thread can leave programs in an unpredictable state where locks owned by the thread aren't freed and resources aren't given back to the OS. Eventually leaving your program open to dead locks, memory leaks that can't be freed, and potentially affecting the stability of the OS as well too. This really isn't any different if you were in C or any other language because stopping native threads has these problems. Remember threads aren't processes they share memory and state with other threads so they must behave and cooperate.

Java works on interrupting threads as opposed to killing threads so threads must conform to this model when you write them. Therefore, while(true) in your program is bad practice. Instead you need to see if your thread has been interrupted, and shutdown on it's own. Either with Thread.sleep and handling the InterruptedException properly. Or checking Thread.isInterrupted() in your while loop.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值