在Application Server中进行线程处理

mai*_*rgs 12 java multithreading ejb glassfish application-server

我有一个Java程序/线程,我想部署到Application Server(GlassFish).该线程应作为"服务"运行,该服务在Application Server启动时启动,在Application Server关闭时停止.

我该怎么做呢?它实际上不是会话Bean或MDB.这只是一个主题.

Sar*_*tha 7

我只用Tomcat做过这个,但它应该在Glassfish中运行.

创建一个实现的Listener类javax.servlet.ServletContextListener,然后将其放在web.xml中.当您的Web应用程序启动并销毁时,它会收到通知.

一个简单的Listener类:

public class Listener implements javax.servlet.ServletContextListener {

    MyThread myThread;

    public void contextInitialized(ServletContextEvent sce) {
        myThread = new MyThread();
        myThread.start();
    }

    public void contextDestroyed(ServletContextEvent sce) {
        if (myThread != null) {
            myThread.setStop(true);
            myThread.interrupt();
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

这是在你的上一个'context-param'之后和你的第一个'servlet'之前的web.xml中:

<listener>
    <listener-class>atis.Listener</listener-class>
</listener>
Run Code Online (Sandbox Code Playgroud)

不知道是否推荐这种东西,但过去它对我来说效果很好.