【发布时间】:2019-12-05 08:02:35
【问题描述】:
以下代码使用了 2 个异步函数调用:
import kotlinx.coroutines.*
import kotlin.system.*
fun main() = runBlocking<Unit> {
val time = measureTimeMillis {
val one = async { doSomethingUsefulOne() }
val two = async { doSomethingUsefulTwo() }
println("The answer is ${one.await() + two.await()}")
}
println("Completed in $time ms")
}
suspend fun doSomethingUsefulOne(): Int {
delay(3000L) // pretend we are doing something useful here
println("first")
return 13
}
suspend fun doSomethingUsefulTwo(): Int {
delay(1000L) // pretend we are doing something useful here, too
println("second")
return 29
}
println 导致“first”首先打印,然后是“second”。但是根据文档,这些异步应该同时运行。但是既然第一个有3秒的延迟,为什么它的println先运行呢?事实上,我将 println 放在延迟之前还是之后都没有关系。我得到了同样的结果。
【问题讨论】:
-
在我的系统上,它的行为与预期的一样。
second在first之前打印。最后打印出The answer is 42和Completed in 3022 ms。您确定您的观察结果属于显示的代码吗? -
你可以在网上试一下代码here
标签: kotlin