java - 如何使用 Web 应用程序运行不确定的后台进程/线程

标签 java jakarta-ee web-applications glassfish

我希望能够从 Web 应用程序启动/暂停/退出后台进程。我希望该过程无限期地运行。

用户将访问网页。按一个按钮启动线程,它将继续运行,直到用户告诉它停止。

我正在尝试确定执行此操作的最佳工具。我研究过 Quartz 之类的东西,但没有看到任何关于 Quartz 之类的东西是否适合无限线程的讨论。

我的第一个想法是做这样的事情。

public class Background implements Runnable{
    private running = true;

    run(){
         while(running){
              //processing 
        }
    }

    stop(){
        running = false;
    }
}

//Then to start
Background background = new Background();
new Thread(background).start();
getServletContext().setAttribute("background", background);

//Then to stop
background = getServletContext().getAttribute("background");
background.stop();

我要测试一下。但我很好奇是否有更好的方法来实现这一点。

最佳答案

首先,放入 Context 的所有对象都必须实现Serialized

我不建议将 Background 对象放入上下文中,而是创建一个带有 private boolean running = true; 属性的 BackgroundController 类。 getter 和 setter 应该同步,以防止后台线程和 Web 请求线程发生冲突。同样,private boolean Stopped = false; 应该放入同一个类中。

我还做了一些其他更改,您必须将循环核心分解为小单元(例如 1 次迭代),以便可以在 Activity 中间的某个位置停止该过程。

代码如下所示:

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();

关于java - 如何使用 Web 应用程序运行不确定的后台进程/线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14327753/

相关文章:

Java EE 条件过滤器映射

jakarta-ee - SecurityContext不适用于@RolesAllowed

java - Spring 环境差异

java - 整合多个部署的 Java webapp 配置文件的策略

iPhone Web 应用程序输入字段在位置 :absolute container

java - Android - 读取类内的 build.gradle 属性

java - apache Zookeeper kafka 路径

web-applications - 移动应用程序开发 - HTML5 LocalStorage vs SessionStorage vs Cookies

java - Java 中垃圾收集的频率是多少?

java - 使用 IntelliJ 创建 Java 样板代码