Tomcat:shutdown.sh的残留
现象:在Linux下,使用shutdown.sh来关闭Tomcat,web服务确实已经关闭了,但是在线程中仍然存在Tomcat,只能使用kill杀死。原因:在web系统中,如果有后台线程打开Socket客户端,用shutdown.sh是关闭不掉Tomcat的。
解决方法:
一般情形下,一个后台线程往往是和web程序一起启动的,这时候我们的做法就是添加一个类继承ServletContextListener,然后重写它的
public void contextInitialized(ServletContextEvent arg0)方法,在它里面关闭后台线程。
在Web服务(启动)的时候,启动一个线程,有以下两种方法:
第一种方法:使用ServletContextListener,具体如下:
ServletContextListener
web.xml中添加以下行
com.mypackage.MyServletContextListener
下面是一个例子:
public class MyServletContextListener implements ServletContextListener {
private MyThreadClass myThread = null;
public void contextInitialized(ServletContextEvent sce) {
if ((myThread == null) || (!myThread.isAlive())) {
myThread = new MyThreadClass();
myThread.start();
}
}
public void contextDestroyed(ServletContextEvent sce){
try {
myThread.doShutdown();
myThread.interrupt();
} catch (Exception ex) {
}
}
}
第二种方法:在Servlet的init()方法中创建线程,具体例子:
web.xml中添加以下行:特别需要注意的是设置load-on-startup为1,使得MyServlet可以在war部署时就加载
MyServlet
MyServlet
com.test.MyServlet
1
Servlet中init方法例子:
public void init() throws ServletException {
super.init();
//start debugger in a new thread
Thread thread = new Thread(new Runnable() {
public void run() {
try {
System.out.println("do anything you like...");
} catch (Exception e) {
e.printStackTrace();
}
System.out.print("debugger started.#");
}
});
thread.start();
}
页:
[1]