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停止时如何停止线程?
最佳答案
在 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();
}
}
.
关于java - tomcat停止时如何停止线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45671444/