使用 fixedRateTimer 时 Kotin 应用程序不会停止(即使 window 已关闭)

Kotin application won't stop when using fixedRateTimer (even when window is closed)

我在 Kotlin 中有一个简单的应用程序,它绘制一个矩形,然后使用 fixedRateTimer 以每秒 30 次的频率更新矩形的位置。我遇到的问题是,当我关闭显示矩形的 window 时,应用程序保持 运行ning 并且我必须按下 Intellij 中的红色方块才能真正停止它。

我曾尝试在关闭 window 之前取消 fixedRateTimer,但应用程序仍在 运行ning 它似乎什么也没做。如果我 运行 没有 fixedRateTimer 的应用程序它只显示正方形然后当我关闭 window 它停止应用程序。

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 以创建守护线程,或者确保保存从 fixedRateTimer() 调用返回的 Timer 实例,并在某个时候调用 cancel 以停止来自 运行 退出前计时器的非守护线程。

当有守护线程运行时,JVM 会退出,但当有非守护线程时,JVM 不会退出。