你的线程类
public class MyDaemon implements Runnable {
private volatile boolean running = false;
public void setRunning(boolean isRunning){
this.running = isRunning;
}
public boolean isRunning(){
return running ;
}
public void run(){
**running = true;**
while(running){
// your code here
}
}
}
线程异常处理程序将在异常情况下重置变量
public class ThreadExceptionHandler implements Thread.UncaughtExceptionHandler {
private Thread thread;
private Throwable exception;
public void uncaughtException(Thread t, Throwable e) {
thread = t;
exception = e;
thread.setRunning(false);
}
}
您的 Start/Stop 方法将从 ServletContext 获取变量并检查 isRunning 方法。然后使用 setRunning() 方法。
已编辑
你的代码应该是
Thread dt = (Thread)this.getServletContext().getAttribute("myDaemon");
if(dt != null){
if (dt.isRunning()){
// Running so you can only check STOP command
if (yourCommand == 'STOP'){
dt.setRunning(false);
}
}
else {
// Not Running so check START command
if (yourCommand == 'START'){
dt.start();
}
}
}
else{
// First time
// create exception handler for threads
ThreadExceptionHandler threadExceptionHandler = new ThreadExceptionHandler();
// start Daemon thread
Thread dThread = new Thread(new MyDaemon (), "Daemon");
dThread.setUncaughtExceptionHandler(threadExceptionHandler);
dThread.setDaemon(true);
dThread.start();
// now save this dThread so servlet context
this.getServletContext().setAttribute("myDaemon", dThread);
}
我希望这会有所帮助。