fix*_*ate 5 multithreading javafx task
我正在编写JavaFX应用程序,我的对象扩展Task以提供远离JavaFX GUI线程的并发性.
我的Main类看起来像这样:
public class MainApp extends Application {
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("Sample.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
public void handle(WindowEvent t) {
//I have put this in to solve the threading problem for now.
Platform.exit();
System.exit(0);
}
});
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Run Code Online (Sandbox Code Playgroud)
我的GUI控制器示例看起来像这样(稍微抽象):
ExecutorService threadPool = Executors.newFixedThreadPool(2);
private void handleStartButtonAction(ActionEvent event) {
MyTask task = new MyTask();
threadPool.execute(task);
}
Run Code Online (Sandbox Code Playgroud)
目前,我的任务只是睡眠并打印数字1到10:
public class MyTask extends Task<String> {
@Override
protected String call() throws Exception {
updateProgress(0.1, 10);
for (int i=0;i<=10;i++) {
if (isCancelled()) {
break;
}
Thread.sleep(1000);
System.out.println(i);
updateProgress(i, 10);
}
return "Complete";
}
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是,一旦任务完成,就好像启动任务的线程继续运行一样.因此,当我通过按"X"右上角退出JavaFX应用程序时,JVM继续运行,我的应用程序不会终止.如果你看看我的主类,我已经放入了System.exit(),这似乎解决了问题,虽然我知道这不是正确的方法.
有人可以建议我在终止我的子线程方面需要做什么,以及这样做的可接受方式是什么?即检查它们是否完整然后终止.
谢谢