https://blog.csdn.net/it_beecoder/article/details/78446747
https://blog.csdn.net/soonfly/article/details/70917204
JavaWeb 服务启动时,在后台启动加载一个线程。
目前,我所掌握的一共有两种方法,第一种是监听(Listener),第二种是配置随项目启动而启动的Servlet。
监听(Listener)
首先,我们创建一个监听的类,继承ServletContextListener,如下:
publicclass MyListener implements ServletContextListener {
private MyThread myThread;
publicvoid contextDestroyed(ServletContextEvent e) {
if (myThread != null && myThread.isInterrupted()) {
myThread.interrupt();
}
}
publicvoid contextInitialized(ServletContextEvent e) {
String str =null;
if (str == null && myThread == null) {
myThread =new MyThread();
myThread.start();// servlet 上下文初始化时启动 socket
}
}
}
/**
* 自定义一个 Class 线程类继承自线程类,重写 run() 方法,用于从后台获取并处理数据
*
* @author Champion.Wong
*
*/
class MyThread extends Thread {
publicvoid run() {
while (!this.isInterrupted()) {// 线程未中断执行循环
try {
Thread.sleep(2000); //每隔2000ms执行一次
}catch (InterruptedException e) {
e.printStackTrace();
}
// ------------------ 开始执行 ---------------------------
System.out.println("____FUCK TIME:" + System.currentTimeMillis());
}
}
}
然后,在web.xml中配置如下:
<listener><listener-class>com.wxp.thread.MyListener</listener-class></listener>
方式二:
使用Servlet,在项目启动的时候启动它。
首先,创建一个Servlet,继承HttpServlet
publicclass MyServlet extends HttpServlet{
privatestaticfinallong serialVersionUID = 1L;
private MyThread1 myThread1;
public MyServlet(){
}
publicvoid init(){
String str =null;
if (str == null && myThread1 == null) {
myThread1 =new MyThread1();
myThread1.start();// servlet 上下文初始化时启动 socket
}
}
publicvoid doGet(HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse)
throws ServletException, IOException{
}
publicvoid destory(){
if (myThread1 != null && myThread1.isInterrupted()) {
myThread1.interrupt();
}
}
}
class MyThread1 extends Thread {
publicvoid run() {
while (!this.isInterrupted()) {// 线程未中断执行循环
try {
Thread.sleep(2000);
}catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("____FUCK TIME:" + System.currentTimeMillis());
}
}
}
然后,在web.xml中配置 :
<servlet><servlet-name>MyListener</servlet-name><servlet-class>com.ite.wxp.MyServlet</servlet-class><load-on-startup>9</load-on-startup><!-- 数字越小,启动的优先级越高,必须大于0 --></servlet><servlet-mapping><servlet-name>MyListener</servlet-name><url-pattern>/test</url-pattern></servlet-mapping>
网友评论