gpt4 book ai didi

kotlin - 使用 fixedRateTimer 时 Kotin 应用程序不会停止(即使窗口关闭)

转载 作者:行者123 更新时间:2023-12-02 12:21:45 24 4
gpt4 key购买 nike

我在 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创建一个守护线程,或者确保你保存了 TimerfixedRateTimer() 返回的实例调用,并在某个时候调用 cancel在它上面停止非守护进程线程在你退出之前运行计时器。

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

关于kotlin - 使用 fixedRateTimer 时 Kotin 应用程序不会停止(即使窗口关闭),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58080453/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com