如果你希望在war包部署(启动)的时候,启动一个线程,有以下两种方法:
第一种方法:使用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方法例子:
- // This Happens Once and is Reused
- 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();
- }
阅读(5597) | 评论(0) | 转发(0) |