【发布时间】:2014-09-21 13:32:46
【问题描述】:
对于 JavaFX UI 控制器事件,我想暂停后台服务,该服务以该 UI 控制器开始(如以下代码所示)。
我发现了一个类似的帖子JavaFX2: Can I pause a background Task / Service。但是在那篇文章中,它将提供使用自己的事件暂停服务的解决方案,而不是使用外部 UI 控制器触发的事件。
实际上在这种情况下,我似乎必须设置服务的内部状态以使其暂停,但工作接口不包含这样的状态。举个例子,我们可以强制让服务失败,它的状态为失败等。
谢谢。
UI 控制器类
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;
}
}
}
}
【问题讨论】:
标签: java multithreading service concurrency javafx