你的线程类
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);
}
}
你开始/停止方法得到ServletContext的变量,并检查isRunning方法。然后使用setRunning()方法。
EDITED
你的代码应该是
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);
}
我希望帮助。
谢谢!我最终使用此代码的修改版本来使其工作。我在我的bean中创建了这个private ServletContext servletContext =(ServletContext)FacesContext.getCurrentInstance()。getExternalContext()。getContext();那么我能够检查它是否运行if(servletContext.getAttribute(“MyDaemon”)== null)...} else {//其运行} – user2229544
编辑我的答案以满足您的要求。请看一看。 – Sujoy