在Servlet的init方法中创建线程
servlet代码如下:
package com.weichat.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //测试执行线程的类 public class TestRunThreadServlet extends HttpServlet implements Runnable{ //init servlet public void init() throws ServletException { System.out.println("开始init..."); Thread thread = new Thread(new TestRunThreadServlet()); thread.start(); } //业务类 public void threadMethod(){ System.out.println("start thread"); try { System.out.println("线程开始休眠"); Thread.sleep(1000*3); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("本次执行完毕"); } @Override public void run() { while(true){ threadMethod(); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("come in post"); System.out.println("go out post"); } }
web.xml中添加servlet注册
<servlet> <servlet-name>TestRunThreadServlet </servlet-name> <display-name>TestRunThreadServlet </display-name> <servlet-class>com.hseact.fecp.servlet.TestRunThreadServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet>