0

我正在使用 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);
            }

        }
    };

问题是,程序完成后,即使我关闭了项目,所以我的数据库也在不断更新。那么当程序关闭时我怎样才能杀死线程呢?

谢谢

4

2 回答 2

2

据我所知,您应该向AppServletContextListener被调用的contextDestroyed(ServletContextEvent). 将您的zamanli对象存储为AppServletContextListener类的实例变量,并使用该contextDestroyed方法停止zamanli.

但总的来说,我建议不要在 Java EE 环境中启动自己的线程。

于 2013-07-12T10:47:29.977 回答
2

使用 aScheduledExecutorService代替 a Timer,并使用 aThreadFactory生成守护线程而不是普通线程:

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()它即可。

于 2013-07-12T10:48:29.383 回答