【发布时间】:2018-09-20 21:13:55
【问题描述】:
我在 Kotlin 中有以下代码
import kotlinx.coroutines.experimental.async
import kotlinx.coroutines.experimental.delay
import kotlinx.coroutines.experimental.runBlocking
fun main(args: Array<String>) {
runBlocking {
val async1 = async {
println("1st")
delay(2000)
println("1st end")
}
val async2 = async {
println("2nd")
delay(1000)
println("2nd end")
}
async1.await()
async2.await()
println("end")
}
}
输出是
1st
2nd
2nd end
1st end
end
我的理解是,await() 是一个挂起函数,这意味着执行在那里“暂停”。所以我想,实际上首先会执行async1,然后会执行async2。所以我希望输出是
1st
1st end
2nd
2nd end
end
显然发生的事情是,async1 和 async2 都并行执行,这可以看作是 async1 的输出夹在 async2 的输出之间。
所以我现在的具体问题是:为什么 Kotlin 没有在 async1 上暂停,而是同时在 async2 上启动?
【问题讨论】: