Thread.sleep() 在原生 Kotlin 项目中
Thread.sleep() in a native Kotlin project
我正在尝试创建一个简单的原生 Kotlin 项目。我希望我的项目在一个过程中等待 X 毫秒:
import kotlin.concurrent
fun main() {
Thread.sleep(500);
println("Hello world")
}
编译命令:
kotlinc main.kt -o program.exe
但我收到以下错误:
main.kt:1:15: error: unresolved reference: concurrent
import kotlin.concurrent
^
main.kt:4:2: error: unresolved reference: Thread
Thread.sleep(500);
^
我有点懵,这不是延迟申请的正确方法吗?
首先,Kotlin/Native 有 kotlin.native.concurrent
库,这就是第一个错误的原因。但是即使在这个里面,也没有Thread.sleep()
这样的函数。相反,您可以尝试使用 K/N 的 POSIX built-in 库中的 platform.posix.sleep()
函数。我不确定这种方法的用例是什么,但是如果您真的需要保留线程,这可能会有所帮助。
如果您需要比秒更精确,您可以像这样使用 nanosleep
函数:
import platform.posix.nanosleep
import platform.posix.timespec
// ...
val time = cValue<timespec> {
tv_sec = 2
tv_nsec = 500000000
}
nanosleep(time, null)
tv_sec
是睡眠的秒数
tv_nsec
是睡眠的额外纳秒数(0 到 999999999)
以上示例等待 2.5 秒。
我正在尝试创建一个简单的原生 Kotlin 项目。我希望我的项目在一个过程中等待 X 毫秒:
import kotlin.concurrent
fun main() {
Thread.sleep(500);
println("Hello world")
}
编译命令:
kotlinc main.kt -o program.exe
但我收到以下错误:
main.kt:1:15: error: unresolved reference: concurrent
import kotlin.concurrent
^
main.kt:4:2: error: unresolved reference: Thread
Thread.sleep(500);
^
我有点懵,这不是延迟申请的正确方法吗?
首先,Kotlin/Native 有 kotlin.native.concurrent
库,这就是第一个错误的原因。但是即使在这个里面,也没有Thread.sleep()
这样的函数。相反,您可以尝试使用 K/N 的 POSIX built-in 库中的 platform.posix.sleep()
函数。我不确定这种方法的用例是什么,但是如果您真的需要保留线程,这可能会有所帮助。
如果您需要比秒更精确,您可以像这样使用 nanosleep
函数:
import platform.posix.nanosleep
import platform.posix.timespec
// ...
val time = cValue<timespec> {
tv_sec = 2
tv_nsec = 500000000
}
nanosleep(time, null)
tv_sec
是睡眠的秒数tv_nsec
是睡眠的额外纳秒数(0 到 999999999)
以上示例等待 2.5 秒。