【问题标题】:Executors or threads keep program from shutting down执行器或线程阻止程序关闭
【发布时间】:2017-01-21 12:15:33
【问题描述】:

在我的程序中创建了一些线程并给出了一个结束的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?我找不到关闭它的方法。

我还应该做什么其他清理工作?

【问题讨论】:

  • 在您尝试退出后检查线程转储(或使用诸如 visualvm 之类的工具)并查看仍在运行的内容。
  • @NicolasFilotto 这不是我无法关闭的服务,而是newSingleThreadExecutor
  • 它是一回事,它只是你在重复答案中的一个特定用例
  • 我会做一个线程转储来确定哪些非守护线程实际上仍在运行

标签: java multithreading javafx javafx-8


【解决方案1】:

是的,这正是因为您没有在 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();

【讨论】:

  • 好的,它没有shutdown方法,那你怎么关闭它?
  • 我在另一个答案中读到System.exit(0); 并没有真正关闭程序......
  • 你从Executors获取的服务有一个关闭方法
  • 但我不使用服务,我使用:private Executor XExecutor = Executors.newSingleThreadExecutor(); 它不想做ScheduledExecutorService service = XExecutor;
  • 对不起,应该是:私人ScheduledExecutorService XExecutor = Executors. newSingleThreadScheduledExecutor();
猜你喜欢
  • 2021-05-05
  • 2023-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多