ExecutorService is not shutting down

匿名 (未验证) 提交于 2019-12-03 09:05:37

问题:

I have the following code

    ExecutorService es = Executors.newSingleThreadExecutor();     es.submit(new Runnable() {            @Override public void run()             {                   while(true);              }    });  es.shutdownNow(); 

The problem is that the ExecutorService doesn't shutdown after I call shutdownNow. Documentation says that it Attempts to stop all actively executing tasks.

So why is the ES failing to shutdown?

回答1:

I did this and it worked:

    ExecutorService es = Executors.newSingleThreadExecutor();     es.submit(new Runnable() {            @Override public void run()             {                   while(!Thread.currentThread().isInterrupted());              }    });     es.shutdownNow(); 

the reason is that shutdownNow doesn't terminate the thread. it just interrupts all running threads.



回答2:

You can't shut down a thread that just refuses to terminate. It's just like you cannot force a thread to terminate, when it is running an infinite loop.

From the Javadoc for shutdownNow(): "There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. For example, typical implementations will cancel via Thread.interrupt(), so any task that fails to respond to interrupts may never terminate."

So unless your thread responds to an interrupt (see http://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html), there's not much else shutdownNow() can do to terminate a thread.



回答3:

The key phrase in the documentation is "attempts to". By having simple while(true) in the loop, you give the thread no chance to be interrupted. Try putting a sleep() call in the loop.



回答4:

isInterrupted() returns true if and only if thread's execution is interrupted.

     ExecutorService es = Executors.newSingleThreadExecutor();         es.submit(new Runnable() {                @Override public void run()                 {   // infinite loop to process                         while(true)                        {                                                         // We've been interrupted: no more processing.                           if(Thread.currentThread().isInterrupted()){                              return;                            }                        }                  }        });    es.shutdownNow(); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!