当tomcat停止时如何停止线程

时间:2017-08-14 09:30:40

标签: java multithreading tomcat

java代码

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停止时如何停止线程?

1 个答案:

答案 0 :(得分:0)

在contextDestroyed上的servletcontextlistener中对执行程序服务调用shutdownNow,这将中断池中的线程。看到这个问题: how to catch the event of shutting down of tomcat?

但是你的Customer Runnable并没有停止响应中断所做的事情,因此关闭线程池不会导致它退出。更改Customer的run方法以在检测到中断标志时退出循环:

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