执行程序或线程使程序无法关闭

时间:2016-09-13 19:37:08

标签: java multithreading javafx javafx-8

在我的程序中创建了一些线程,并给出了一个结束的Task(这样线程就会死掉),而且我还有一个Executors.newSingleThreadScheduledExecutorExecutors.newSingleThreadExecutor,我注意到如果我按下我做的关闭按钮:

@FXML private void handleExit(){
    gameManager.cleanup();
    Stage stage = (Stage)menuBarTopMenu.getScene().getWindow();
    Platform.exit();
    stage.close();
}

我没有在intelij中获得Process finished with exit code 0

所以我甚至将我提到的那些线程设置为守护进程,这是清理:

public void cleanup(){
    updateTime.shutdown();  // it's Executors.newSingleThreadScheduledExecutor
    updateTime.shutdownNow();
}

但我仍然没有看到成功的退出。可能是因为我没有关闭Executors.newSingleThreadExecutor?我无法找到一种方法来关闭它。

我应该做什么其他清理?

1 个答案:

答案 0 :(得分:3)

是的,这正是因为你没有在newSingleThreadExecutor上调用shutdown,但是如果你有其他正在运行的线程,他们也可以阻止应用程序退出。要强制VM关闭(所有线程都将终止),您可以调用System.exit(0);

你将Executor服务包装成:

ExecutorService service = Executors.newSingleThreadScheduledExecutor();

\\ use the service to do work
\\ to shutdown the service
service.shutdown();

\\ to wait till the service terminate
service.awaitTermination();