你的線程類
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