可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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();