首页 > 代码库 > 在Servlet的init方法中创建线程
在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方法中创建线程
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。