2017-08-14 233 views
1

Java代碼如何停止線程當Tomcat停止

static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 10, 0l, TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>()); 

threadPoolExecutor.execute(customer); 

class Customer implements Runnable { 

    @Override 
    public void run() { 
     while (true) { 
      try { 
       Thread.sleep(5000); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

} 

tomcat的停止線,但仍然活着;
如何在tomcat停止時停止線程?

+0

調用ThreadPool。[shutdownNow()](https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html#shutdownNow())方法 – Stefan

回答

0

在contextDestroyed上的servletcontextlistener中的executor服務上調用shutdownNow,這將中斷池中的線程。看到這個問題: how to catch the event of shutting down of tomcat?

但是,您的Customer Runnable不會停止它響應中斷所做的事情,因此關閉線程池不會導致它退出。將客戶的運行方法更改爲在檢測到中斷標誌時退出循環:

while (!Thread.currentThread().isInterrupted()) { 
    try { 
     Thread.sleep(5000); 
    } catch (InterruptedException e) { 
     Thread.currentThread().interrupt(); 
    } 
}