首先,所有Object
放入 Context 的 s 都必须实现Serializable
.
我不建议将Background
对象放入上下文中,而是创建一个BackgroundController
具有private boolean running = true;
属性的类。getter 和 setter 应该是synchronised
,以防止后台线程和 web 请求线程发生冲突。同样,private boolean stopped = false;
应该将它们放在同一个类中。
我还进行了一些其他更改,您必须将循环核心分解为小单元(如 1 次迭代),以便可以在活动中间的某个位置停止进程。
代码如下所示:
public class BackgroundController implements Serializable {
private boolean running = true;
private boolean stopped = false;
public synchronized boolean isRunning() {
return running;
}
public synchronized void setRunning(boolean running) {
this.running = running;
}
public synchronized boolean isStopped() {
return stopped;
}
public synchronized void stop() {
this.stopped = true;
}
}
public class Background implements Runnable {
private BackgroundController control;
public Background(BackgroundController control) {
this.control = control;
}
run(){
while(!isStopped()){
if (control.isRunning()) {
// do 1 step of processing, call control.stop() if finished
} else {
sleep(100);
}
}
}
}
//Then to start
BackgroundController control = new BackgroundController();
Background background = new Background(control);
new Thread(background).start();
getServletContext().setAttribute("backgroundcontrol", control);
//Then to pause
control = getServletContext().getAttribute("backgroundcontrol");
control.setRunning(false);
//Then to restart
control = getServletContext().getAttribute("backgroundcontrol");
control.setRunning(true);
//Then to stop
control = getServletContext().getAttribute("backgroundcontrol");
control.stop();