簡體   English   中英

關閉項目后線程仍然退出,如何將其殺死?

[英]Thread still exits after closing project, how to kill it?

我正在使用jsf編寫Java EE應用程序。 我定義了一些后台流程,例如定期更新數據庫等。下面是代碼:

public class AppServletContextListener implements ServletContextListener{
    @Override
public void contextInitialized(ServletContextEvent arg0) {
    zamanli zm = new zamanli();
        try {   
            zm.programBasla();
        } catch (MalformedURLException ex) {
            Logger.getLogger(AppServletContextListener.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(AppServletContextListener.class.getName()).log(Level.SEVERE, null, ex);
        }
}       
}

和班級:

public class zamanli {
    public void programBasla() throws MalformedURLException, IOException {
    int delay = 5000; //5 sn sonra başlar
    int period = 600000; //10 dkda tekrar
    Timer timer = new Timer();
    TimerTask task = new TimerTask() {
        @Override
        public void run() {

            Runtime r = Runtime.getRuntime();
            Process p = null;

            try {
                //  p = r.exec("c:\\WINDOWS\\system32\\calc");
                System.out.println(Now());

            } catch (Exception e) {

                System.out.println("Çalışmadı");
            }
            try {
                getCurrentExchangeValue();
            } catch (MalformedURLException ex) {
                Logger.getLogger(zamanli.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(zamanli.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    };

問題是,在程序完成后,即使我關閉了項目,所以我的數據庫也在不斷更新。 那么當程序關閉時我如何殺死線程?

謝謝

據我所知,您應該在AppServletContextListener添加一個名為contextDestroyed(ServletContextEvent) zamanli對象存儲為AppServletContextListener類的實例變量,並使用contextDestroyed方法停止zamanli

但總的來說,我建議不要在Java EE環境中啟動自己的線程。

使用ScheduledExecutorService代替Timer ,並使用ThreadFactory生成守護進程線程而不是普通線程:

private static final ThreadFactory THREAD_FACTORY = new ThreadFactory()
{
    private final ThreadFactory factory = Executors.defaultThreadFactory();

    @Override
    public Thread newThread(final Runnable r)
    {
        final Thread ret = factory.newThread(r);
        ret.setDaemon(true);
        return ret;
    }
};

// ...
private final ScheduledExecutorService service
    = Executors.newSingleThreadScheduledExecutor(THREAD_FACTORY);

//...
service.scheduleAtFixedRate(etc etc);

使得service引用可用於contextDestroyed() ,這將更加容易; 然后,您不必使用守護程序線程,而只需在其中調用service.shutdownNow()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM