ExecutorService is not shutting down

前端 未结 5 469
独厮守ぢ
独厮守ぢ 2021-01-13 06:17

I have the following code

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


        
相关标签:
5条回答
  • 2021-01-13 06:49

    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.

    0 讨论(0)
  • 2021-01-13 06:54

    Please try this

    ExecutorService es = Executors.newSingleThreadExecutor();
    es.submit(new Runnable() {
           @Override public void run() 
           {
                 try{
                    while(true);
                 }catch(InterruptException){
                    Thread.currentThread().interrupt();
                 }
            }
    

    }); es.shutdownNow();

    0 讨论(0)
  • 2021-01-13 07:02

    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();
    
    0 讨论(0)
  • 2021-01-13 07:04

    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.

    0 讨论(0)
  • 2021-01-13 07:11

    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.

    0 讨论(0)
提交回复
热议问题