【发布时间】:2022-06-10 20:24:54
【问题描述】:
我只想等两三秒,我知道用Java怎么做,我试过了,但不知道kotlin
一些简单的东西:
println("hello")
// a 2 seconds delay
println("world")
【问题讨论】:
-
你尝试了什么?发生了什么?
我只想等两三秒,我知道用Java怎么做,我试过了,但不知道kotlin
一些简单的东西:
println("hello")
// a 2 seconds delay
println("world")
【问题讨论】:
这很简单。只需使用协程即可。像这样:
fun main() = runBlocking {
launch {
delay(2000L)
println("World!")
}
println("Hello")
}
不要忘记像这样导入 kotlin 协程:
import kotlinx.coroutines.*
在 kotlin 中编码愉快!!!
【讨论】:
有一些方法:
1- 使用处理程序(基于毫秒)(已弃用):
println("hello")
Handler().postDelayed({
println("world")
}, 2000)
2- 使用执行器(基于秒):
println("hello")
Executors.newSingleThreadScheduledExecutor().schedule({
println("world")
}, 2, TimeUnit.SECONDS)
3- 使用定时器(基于毫秒):
println("hello")
Timer().schedule(2000) {
println("world")
}
【讨论】:
如果您不想使用任何依赖项,则可以使用Thread.sleep(2000L)
这里,1 秒 = 1000L
代码应该是这样的,
println("hello")
Thread.sleep(2000L)
println("world")
【讨论】: