Original posts: http://blog.163.com/[email protected]/blog/static/1806962120124285346297/
How do you open a background thread while Java Web development is executing as Tomcat starts?
You can refer to the following steps:
1. First define class in the project to inherit the Servletcontextlistener interface, and define the thread and thread functions, the following example code:
Packagetest;Importjavax.servlet.*; Public classMyCodeImplementsServletcontextlistener {//when Tomcat starts, it executes contextinitialized () Public voidcontextinitialized (servletcontextevent e) {NewMyThread (). Start (); } Public voidcontextdestroyed (Servletcontextevent e) {}
//define a thread and set it to the corresponding thread function run () classMyThreadextendsThread { Public voidrun () {System.out.println ("Test Start"); } } }
2. You will then need to add the following on the project's Web. xml
< Listener > <listnenr-class></listener-class> </listener>
OK, you can try it, too.
Start a thread with Tomcat (GO)