首页 > 解决方案 > 如何防止 Timer 在后台运行?

问题描述

我正在使用 JavaFX 8 开发一个小游戏作为辅助项目,我想使用包中的TimerJava.util

问题是,每当我安排Timer做某事时,我不知道如何停止它,即使我已经关闭了窗口,它也会继续在后台运行。

我最终使用下面的代码创建了一个方法handleShutDown(),只要Stage设置为隐藏,就会调用该方法。

stage.setOnHidden(windowEvent -> controller.handleShutDown());

我还尝试了几种不同的方法来取消方法Timer中的handleShutDown()。我尝试调用 Timer 的cancel()方法,Timer 的purge()方法,将 Timer 设置为null,甚至将 Timer 替换为新的(timer = new Timer())。

public void handleShutDown() {
//    timer.cancel();
//    timer.purge();
//    timer = new Timer();
    timer = null;
    Platform.exit();
}

我不确定接下来要尝试什么...

这是我知道应用程序仍在运行的方式,因为即使在我关闭窗口后红框仍然存在,这不应该发生。在我开始使用计时器之前一切都很好。或者也许我不应该使用定时器?

这是我知道应用程序仍在运行的方式

提前致谢。

标签: javajavafxtimer

解决方案


Thread在后台运行并在主线程终止时终止,请使用daemon布尔属性(请参阅:守护线程):

Thread thread = new Thread();
thread.setDaemon(true); // this thread will die when the main thread dies 

Timer使用TimerThread扩展了 Java 的Thread. 使用无参数构造函数构造定时器时,底层线程默认为非守护线程。要使时间在守护线程上运行,您可以使用Timer的构造函数:

Timer timer = new Timer(true); // a timer with a daemon thread.

推荐阅读