I am writing a JavaFX application and my objects extend the Task to provide concurrency from the JavaFX GUI thread.
My main class is as follows:
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) {
Platform.exit();
System.exit(0);
}
});
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
My sample GUI controller looks like this (abstracted):
ExecutorService threadPool = Executors.newFixedThreadPool(2);
private void handleStartButtonAction(ActionEvent event) {
MyTask task = new MyTask();
threadPool.execute(task);
}
At the moment, my task is simply doing sleep mode and printing numbers from 1 to 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";
}
}
The problem that I encountered is when the task is completed, it appears as if the thread with which the task is running continues to work. Therefore, when I exit the JavaFX application by clicking the upper right corner of the “X”, the JVM continues to work, and my application does not exit. If you look at my main class, I put System.exit (), which seems to solve the problem, although I know this is not the right way.
- , , ? , , , , .