2017-08-14 217 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(); 
    } 
}