收藏
原文链接:http://blog.csdn.net/it_wangxiangpan/article/details/7168286
JavaWeb 服务启动时,在后台启动加载一个线程。
目前,我所掌握的一共有两种方法,第一种是监听(Listener),第二种是配置随项目启动而启动的Servlet。
下面对这两种方法做一简单的介绍,(Mark一下,防止以后急用又忘记了):
监听(Listener)首先,我们创建一个监听的类,继承ServletContextListener,如下:
package com.wxp.thread;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
* Listener的方式在后台执行一线程
*
* @author Champion.Wong
*/
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() 方法,用于从后台获取并处理数据
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());
<listener>
<listener-class>com.wxp.thread.MyListener</listener-class>
</listener>
使用Servlet,在项目启动的时候启动它。首先,创建一个Servlet,继承HttpServlet
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ite.common.Constants;
publicclass MyServlet extends HttpServlet{
privatestaticfinallong serialVersionUID = 1L;
private MyThread1 myThread1;
public MyServlet(){
publicvoid init(){
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 {
Thread.sleep(2000);
<!-- LISTENER FOR THREAD -->
<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>
<url-pattern>/test</url-pattern>
</servlet-mapping>
其中,Listener的方式,该线程肯定是项目中首先启动的,优先于任何一个Servlet。而Servlet的方式,可以设置与其它Servlet启动的顺序。如果有时候需要首先启动一个Servlet或者它们之间的启动顺序有特殊要求的时候,这个就很有作用了。
转载于:https://blog.51cto.com/jormin/1358552