web.xml 檔:
<web-app>
<listener>
<listener-class>com.main.Main</listener-class> <!-- Main.java 路徑 -->
</listener>
</web-app>
Main.java 檔:
package com.main;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class Main implements ServletContextListener {
private MyThreadClass myThread = null;
@Override
public void contextInitialized(ServletContextEvent sce) {
if ((myThread == null) || (!myThread.isAlive())) {
myThread = new MyThreadClass();
myThread.start(); // Tomcat 啟動時建立新 Thread
}
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
myThread.doShutdown(); // Tomcat 關閉時呼叫此方法
}
}
class MyThreadClass extends Thread {
@Override
public void run() {
System.out.println("My Start");
}
public void doShutdown() {
System.out.println("My Close");
}
}
留言列表