java - tomcat停止时如何停止线程

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

最佳答案

在 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/

相关文章:

c++ - 为什么我不能将数组值返回给主函数?

tomcat - java.lang.UnsatisfiedLinkError : Access denied. 使用 JNI

java - 如何配置 Jersey 以避免 com.sun.jersey.spi.container.servlet.ServletContainer 出现问题?

tomcat - 通过 Tomcat Context LifecycleListener 在 WEB-INF/classes 中加载类

java - 在JAVAFX中将字符串行添加到TableView

java - 字节数组操作

java - 检索下一个可用的自动编号

java - 用于查找重复项的 Hibernate 标准

java线程和操作系统线程

java - Android(在 Scala 中): StackOverflowError depends on when to start a thread?