kotlin - Kotin 应用程序在使用 fixedRateTimer 时不会停止(即使窗口关闭)
问题描述
我在 Kotlin 中有一个简单的应用程序,它绘制一个矩形,然后使用 fixedRateTimer 每秒 30 次更新矩形的位置。我遇到的问题是,当我关闭显示应用程序继续运行的矩形的窗口时,我必须按下 Intellij 内的红色方块才能真正停止它。
我尝试在关闭窗口之前取消 fixedRateTimer,但应用程序仍在运行,它似乎没有做任何事情。如果我在没有 fixedRateTimer 的情况下运行应用程序,它只会显示正方形,然后当我关闭窗口时它会停止应用程序。
import javafx.scene.paint.Color
import tornadofx.*
import kotlin.concurrent.fixedRateTimer
class MyApp: App(MyView::class)
class MyView : View() {
override val root = stackpane {
group {
rectangle {
fill = Color.LIGHTGRAY
width = 600.0
height = 480.0
}
val myRect = rectangle {
fill = Color.BLUEVIOLET
width = 30.0
height = 30.0
x = 100.0
y = 100.0
}
fixedRateTimer("default", false, 0L, 1000/30) {
myRect.x += 1
if(myRect.x > 200) this.cancel()
}
}
}
}
解决方案
您正在取消 TimerTask,但不是计时器。要么通过daemon = true
创建一个守护线程,要么确保保存Timer
从调用返回的实例fixedRateTimer()
,并在某个时候调用cancel
它以在退出之前停止非守护线程运行计时器。
JVM 会在有守护线程运行时退出,但在有非守护线程时不会退出。
推荐阅读
- python - 多进程中的队列被 threading.Timer 阻塞
- python - 从图像中提取文本
- ios - 如何在 iOS 中创建动态文本模板?
- java - 詹金斯问题 - 无法创建本地回购
- itext - 如何实现itext 7表中的列之间的空间?
- java - 抱怨不兼容的类型
- java - 通过pdfbox从pdf文件中提取文本
- linux - 将 apache fop 与更新的 linux 内核一起使用时出现“字形不可用”错误
- php - 在 IIS web.config 中翻译 .htacess
- xamarin.android - 键盘在 Android 7 OS(Xamarin.Android) 上隐藏了对话框的一部分