如何防止计时器在后台运行?

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

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

我最终使用下面的代码创建了一个名为 handleShutDown() 的方法,每当 Stage 设置为隐藏时都会调用该方法。

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

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

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

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

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

如何防止计时器在后台运行?

提前致谢。

wry52885243 回答:如何防止计时器在后台运行?

要使 Thread 在后台运行并在主线程终止时终止,请使用 daemon 布尔属性(参见:Daemon Threads):

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.
本文链接:https://www.f2er.com/17915.html

大家都在问