java - 如何防止 Timer 在后台运行?
问题描述
我正在使用 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()
)。
public void handleShutDown() {
// timer.cancel();
// timer.purge();
// timer = new Timer();
timer = null;
Platform.exit();
}
我不确定接下来要尝试什么...
这是我知道应用程序仍在运行的方式,因为即使在我关闭窗口后红框仍然存在,这不应该发生。在我开始使用计时器之前一切都很好。或者也许我不应该使用定时器?
提前致谢。
解决方案
要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.
推荐阅读
- php - DateTime php 返回错误的日期
- php - 应用引擎 PHP - 自定义域上的 Cron 无法工作(始终指向 apppot)
- asp.net-mvc - Rest API,在客户端生成文件
- c# - XmlException:找不到类型
- python - 使用 Dask 加载多个 CSV 文件时混合列
- typescript - 如何确保类的参数类型实现接口
- amazon-web-services - 使用 lambda 生成 elbv2 属性(具体名称)时,从 Lambda 接收到名称超过 32 个字符的错误
- xml - xslt-1.0 for-each 循环获取所有子元素
- multithreading - 草书:Clojure 的 *out*、不同的 Writer、多线程时的刷新和排序不一致:这是怎么回事?
- linux - bash中的for循环