Tomcat无法在webapp中停止线程

sja*_*der 2 java multithreading servlets

在我的webapp中,我有3个线程,其中tomcat在重新加载时无法停止其中的2个.

严重:Web应用程序[/ myapp]似乎已经启动了一个名为[Thread-8]的线程,但未能阻止它.这很可能造成内存泄漏.mai 08,2013 11:22:40 AM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads

这会导致每次重新加载时CPU使用率上升.

这是tomcat无法停止的一个线程:

我的ServletContextListener中实现的一些代码:

public void contextInitialized(ServletContextEvent event)
{
    final UpdaterThread updaterThread = new UpdaterThread();
    updaterThread.start();
    event.getServletContext().setAttribute("updaterthread", updaterThread);
}

public void contextDestroyed(ServletContextEvent event)
{
    UpdaterThread updaterThread = (UpdaterThread) event.getServletContext().getAttribute("updaterthread");
    if (updaterThread != null)
    {
        updaterThread.stopUpdater();
        updaterThread.interrupt();
        updaterThread = null;
    }
}
Run Code Online (Sandbox Code Playgroud)

以及UpdaterThread的重要部分:

public class UpdaterThread extends Thread implements Runnable
{
    private boolean alive = true;

    @Override
    public void run()
    {
        while(true)
        {
            try
            {
                while (alive)
                {
                    doUpdate();
                    sleep(60*1000);
                }
            }
            catch (InterruptedException ie) {}
            catch (Exception e) {}
        }
    }

    public void stopUpdater()
    {
        alive = false;
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有人知道为什么这个线程不会停止?有没有更好的方法来实现一个线程在特定时间做一些工作?

Nil*_*lsH 5

据我所知,你实际上根本没有停止你的线程.你有两个while循环,你只在设置时停止内部alive = false.外在将永远运行,什么也不做.您也不处理interrupt您的发送,因此也不会终止该线程.

我会做这样的事情:

public void run()
{
    while(alive)
    {
        try
        {
            doUpdate();
            sleep(60*1000);
        }
        catch (InterruptedException ie) {
            alive = false;
        }
    }
} 
Run Code Online (Sandbox Code Playgroud)

此外,如果在创建线程时给你的线程一个正确的名称,你会看到它是否真的是导致Tomcat报告问题的线程.