我在 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()
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
您正在取消 TimerTask,但没有取消计时器。要么传递daemon = true
创建一个守护线程,要么确保保存Timer
从fixedRateTimer()
调用返回的实例,并在cancel
退出之前的某个时刻调用它以阻止非守护线程运行计时器。
当有守护线程运行时,JVM 将退出,但当有非守护线程运行时,JVM 不会退出。
归档时间: |
|
查看次数: |
3773 次 |
最近记录: |