为什么ExecutorService.shutdownNow方法无法阻止线程 [英] Why ExecutorService.shutdownNow method can't stop the thread

查看:677
本文介绍了为什么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();
 }
}

我已经调用了shutdownNow方法,为什么控制台继续打印 - test - ??

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

推荐答案

查看JavaDoc中的Thread.stop(),原因如下:

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

http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Thread.html#stop()

基本上,您的线程必须自行停止,以使您的程序保持安全。只是停止一个线程可能会使程序处于不可预测的状态,在该状态下,线程拥有的锁不会被释放,资源也不会返回给操作系统。最终让您的程序对死锁,内存泄漏无法释放,并可能影响操作系统的稳定性。如果您使用C语言或任何其他语言,这实际上没有任何不同,因为停止本机线程存在这些问题。记住线程不是与其他线程共享内存和状态的进程,因此它们必须表现和合作。

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用于中断线程而不是杀死线程,因此线程必须符合写这个模型的时候。因此,虽然(true)在你的程序中是不好的做法。相反,您需要查看您的线程是否已被中断,并自行关闭。使用Thread.sleep并正确处理InterruptedException。或者在while循环中检查Thread.isInterrupted()。

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.

这篇关于为什么ExecutorService.shutdownNow方法无法阻止线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆