ServletContextListener contextDestroyed不会中断线程

时间:2016-04-22 16:51:10

标签: java multithreading web servletcontextlistener

我想中断由ServletContextListener启动的线程,但在我取消部署Web应用程序后,调用了contextDestroyed方法并执行了线程上的interrupt()但线程仍在工作。

的ServletContextListener

public class WebListener implements ServletContextListener {

    MyThread myThread;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext context = sce.getServletContext();

        context.setAttribute("Users", users);
        myThread = new MyThread();
        myThread.start();
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        sce.getServletContext().removeAttribute("Users");
        myThread.interrupt();
    }
}

线程类

public class MyThread extends Thread {

    public MyThread() {

    }

    @Override
    public void interrupt() {
        super.interrupt(); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void run() {
        while (true) {
            doWork();

            try {
                sleep(10000);
            } catch (InterruptedException ex) {
                Logger.getLogger(MyThread.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

    @Override
    public synchronized void start() {
        super.start(); //To change body of generated methods, choose Tools | Templates.
    }

}

0 个答案:

没有答案