2013-04-30 84 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