JavaFX - 如何使用 UI Controller 事件暂停后台服务?

标签 java multithreading service concurrency javafx

通过 JavaFX UI Controller 事件,我想暂停后台服务,即以该 UI Controller 启动的服务(如以下代码所示)。

我发现了类似的帖子 JavaFX2: Can I pause a background Task / Service 。但在那篇文章中,它将提供使用其自己的事件暂停服务的解决方案,而不是使用外部 UI Controller 触发的事件。

实际上在这种情况下,我似乎必须设置服务的内部状态以使其暂停,但工作器接口(interface)不包含这样的状态。举个例子,我们可以强制服务失败,包括 FAILED 状态等。

谢谢。

UI Controller 类

public class CommandController implements Initializable {

 private CommandService commandService;
 private ExecutorService sequentialServiceExecutor;
 private List<IOCommandService> servicePool = new ArrayList<>();

 @Override
 public void initialize(URL location, Resources resources) {

   doProceedInitialSteps(); 
 }

 private void doProceedInitialSteps() { 

   // Select available IOCommands 
   List<IOCommand> commandList = commandService.getCommands();

   // Initialised ExecutorService on sequential manner
   sequentialServiceExecutor = Executors.newFixedThreadPool(
                1,
                new ServiceThreadFactory()
   );

   for (final IOCommand command : commandList) { 

        IOCommandService service = new IOCommandService(command, this);

        service.setExecutor(sequentialServiceExecutor);

        service.setOnRunning(new EventHandler<IOCommand>() { }

        service.setOnSucceeded(new EventHandler<IOCommand>() { }

        service.setOnFailed(new EventHandler<IOCommand>() { }

        service.start();

        servicePool.add(service);       
   }

 }

 @FXML
 public void onCancel() {

   // TODO: Need to pause current executing IOCommandService until receive the user response from the DialogBox

   // Unless pause current executing IOCommandService, that will over lap this dialog box with IOCommandService related dialog boxes etc  

   Dialogs.DialogResponse response = Dialogs.showWarningDialog();

   if(response.toString.equals("OK") {

   }
 }

}

服务等级

public class IOCommandService extends Service<IOCommand> {

  private IOCommand command;
  private CommandController controller;

  public IOCommandService (IOCommand command, CommandController controller) {
     this.command = command;
     this.controller = controller;
  }

  @Override
  protected Task<IOCommand> createTask() {

    return new Task<IOCommand>() {

        @Override
        protected Integer call() throws Exception {

         // Execute the IO command by,
         // 1) updating some UI components (label, images etc) on CommandController
         // 2) make enable popup some Dialog boxes for get user response  

         return command;            
        }
    }
  }    
}

最佳答案

海吉·查纳,

这里是一个示例,说明如何“暂停”Service 并在关闭Dialog 后恢复它。

这是 FXML ;)

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane id="AnchorPane" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml" fx:controller="de.professional_webworkx.stopservice.FXMLController">
    <children>
        <Button layoutX="126" layoutY="90" text="Click Me!" onAction="#handleButtonAction" fx:id="button" />
        <Label layoutX="126" layoutY="120" minHeight="16" minWidth="69" fx:id="label" />
    </children>
</AnchorPane>

主应用程序

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;


public class MainApp extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("/fxml/Scene.fxml"));

        Scene scene = new Scene(root);

        stage.setTitle("JavaFX and Concurrency");
        stage.setScene(scene);
        stage.show();
    }


    public static void main(String[] args) {
        launch(args);
    }

}

Controller

import java.net.URL;
import java.util.ResourceBundle;
import javafx.application.Platform;
import javafx.concurrent.Worker;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;

public class FXMLController implements Initializable {

    @FXML
    private Label label;
    private MyService ms;
    @FXML
    private void handleButtonAction(ActionEvent event) {
        onCancel();
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        ms = new MyService();
        Platform.runLater(() -> {
            ms.start();
        });
    }    

    public void onCancel() {

        if(ms.getState().equals(Worker.State.RUNNING)) {
            ms.cancel();
        }
        Scene s = new Scene(new Label("Dialog"), 640, 480);
        Stage dialog = new Stage();
        dialog.setScene(s);
        dialog.showAndWait();

        if(!dialog.isShowing()) {
            ms.resume();
        }


    }
}

以及 MyService 类

我在控制台上运行 for 循环并打印出数字。如果我调用 MyServicepause() 方法,我会 cancel() 并在调用 resume() 方法。 Thread.sleep(2000L);我添加只是为了模拟长时间运行的任务。

import javafx.concurrent.ScheduledService;
import javafx.concurrent.Service;
import javafx.concurrent.Task;

/**
 *
 * @author Patrick Ott
 * @version 1.0
 */
public class MyService extends ScheduledService<Void> {

    Task<Void> task;
    int n = 1000000000;
    @Override
    protected Task<Void> createTask() {
        return new Task() {

            @Override
            protected Object call() throws Exception {
                for (int i = 0; i < n; i++) {
                    System.out.println("Halllo " + n);
                    Thread.sleep(2000);
                    n--;
                }
                return null;
            }
        };
    }

    public void pause() {
        this.cancel();
    }

    public void resume() {
        System.out.println("n="+n);
        this.restart();
    }
}

帕特里克

关于JavaFX - 如何使用 UI Controller 事件暂停后台服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25027835/

相关文章:

java - 使用 java api 在 Elasticsearch 中创建索引和添加映射会导致缺少分析器错误

java - 无法正确验证java方法中的平衡括号解析

c - 使用线程刺激赛车游戏

multithreading - Docker sidekiq 比原生操作系统慢得多

android - 从不同的包启动服务

java - 构建包含所有依赖项的 JAR

java - 就像 SQL 中的函数和 JPA 一样

c# - 如何在 Winform 中使用多线程?

Symfony 4 - Composer 更新后,ObjectManager 不存在此类服务

windows - NSSM 不会拾取可执行目录