在Servlet的init方法中创建线程
Posted 庞国明 博客
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在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>
以上是关于在Servlet的init方法中创建线程的主要内容,如果未能解决你的问题,请参考以下文章