通过修改web.xml让服务器重启的问题

通过修改web.xml让服务器重启的问题?
通过修改web.xml让服务器重启时,项目中开启的线程都不会自动的被关闭,只有你自己去传达web容器关闭事件,通知运行中的线程,让其自动关闭。这里我经常使用的是观察者模式,
代码如下:
监听web容器关闭事件,并自启动一个关闭线程来进行关闭操作,因为web容器的关闭时间是有限的。
public class WebContentClose implements ServletContextListener,Runnable {
@Override
public void contextDestroyed(ServletContextEvent arg0) {
Thread executeCloseThread = new Thread(this);
executeCloseThread.start();
}

@Override
public void contextInitialized(ServletContextEvent arg0) {
}

private static List<IThreadClose> closeThread = new ArrayList<>();


public WebContentClose() {
}

public static synchronized void addObserver(IThreadClose o) {
        if (o == null)
            throw new NullPointerException();
        if (!closeThread.contains(o)) {
        closeThread.add(o);
        }
    }

    public static synchronized void deleteObserver(IThreadClose o) {
    closeThread.remove(o);
    }

    public void notifyObservers() {
        Object[] arrLocal;
        synchronized (WebContentClose.class) {
            arrLocal = closeThread.toArray();
        }

        for (int i = arrLocal.length-1; i>=0; i--){
        try{
            ((IThreadClose)arrLocal[i]).setShutdown();
            ((IThreadClose)arrLocal[i]).interrupted();
            } catch(Exception e){
            System.out.println("关闭线程发生错误:" + arrLocal[i].getClass().getName());
            }
        }
    }

@Override
public void run() {

notifyObservers();
}
}


具体的需要关闭的线程:
public class Pojo implements Runnable,IThreadClose {

Thread thread;

public Pojo() {
thread = new Thread(this);
thread.start();
WebContentClose.addObserver(this);
}
@Override
public void run() {
int i =0;
while(true){
                            //在未开始做任何的业务逻辑之前来做是否停止判断
if (shutdown) {
return ;
}
i++;
printThreadInfor();
System.out.println(i);
try {                            Thread.sleep(2000l);
} catch (InterruptedException e) {
}
}
}

public void printThreadInfor(){
Thread currentThread = Thread.currentThread();
System.out.println("线程id" + currentThread.getId()  + "线程名字" + currentThread.getName());
}

private boolean shutdown = false;
@Override
public void setShutdown() {
shutdown = true;
}
@Override
public void interrupted() {
if(thread == null)
return ;
thread.interrupt();
}

}


public interface IThreadClose {
//设置为需要停止
public void setShutdown();

//触发中断,自己去停止
public void interrupted();
}

猜你喜欢

转载自1064319393.iteye.com/blog/2259298
今日推荐