开发者

Why ExecutorService.shutdownNow method can't stop the thread

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开发者_Python百科 print "-- test --" ??


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()

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.


From the JavaDocs, the ExecutorService#shutdownNow method is not guaranteed to actually stop the executing jobs. You're much better off mutating some state variable that the long-running jobs will periodically check and on detecting the change, quit their run loop.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜