Creating a thread in the servlet's Init method

Source: Internet
Author: User

The servlet code is as follows:

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;//test Execution thread's class public class Testrunthreadservlet extends HttpServlet implements runnable{//init servletpublic void Init () throws Servletexception { System.out.println ("Start init ..."); Thread thread = new Thread (new Testrunthreadservlet ()); Thread.Start ();} Business class public void Threadmethod () {System.out.println ("Start thread"); try {System.out.println ("thread begins to hibernate"); Thread.Sleep (1000*3);} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} SYSTEM.OUT.PRINTLN ("This execution is complete");} @Overridepublic 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");}}

  

Add servlet registration in Web. xml

<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>  

  

Creating a thread in the servlet's Init method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.