2013-04-30 87 views
0

我已经创建使用ScheduleThreadPoolExecutor作为这样一个计划代码调用:如何在tomcat关闭时销毁预定的线程?

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来清理这个额外的线程。监听器在单独的程序中运行,所以它有点卡住了。

有没有人知道如何清理这个关闭?

TIA

+1

你可以注入你的'ServletContextListener'实例引用你的'ScheduledThreadPoolExecutor'吗?如果是这样,那么你可以调用'ScheduledThreadPoolExecutor.shutdownNow()'。 – 2013-04-30 08:00:49

回答

2

而不是

ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(1); 

使用构造与线程工厂

ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(1, threadFactory); 

你的线程工厂应生产这是守护线程,以便在关闭这些线程会自动熄灭。你可以使用自己的工厂,或者简单地使用番石榴的ThreadFactoryBuilder