我已经使用 ScheduleThreadPoolExecutor 创建了一个预定的代码调用:
ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(1);
stpe.scheduleAtFixedRate(new Updatey(), 0, 60, TimeUnit.MINUTES);
它运行一个简单的类:
class Update implements Runnable {
public void run() {
//update code here
}
我有一个 ServletContextListener,它在 tomcat 关闭时调用一个方法并执行其他一些整理工作。但我不知道如何使用 java 在关闭时清理这个额外的线程。 Listener 在单独的程序中运行,所以它让我有点卡住了。
有谁知道如何在关闭时清理它?
TIA
最佳答案
代替
ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(1);
使用带线程工厂的构造函数
ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(1, threadFactory);
您的线程工厂应该生产作为守护进程的线程,因此在关闭时这些线程会自动死亡。你可以使用你自己的工厂或者简单地使用 guava 的 ThreadFactoryBuilder .
关于java - 如何在tomcat关闭时销毁预定线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16294937/