【发布时间】:2021-03-18 22:23:55
【问题描述】:
有一个例子:
import kotlinx.coroutines.*
fun main() = runBlocking { // this: CoroutineScope
launch {
delay(200L)
println("Task from runBlocking")
}
coroutineScope { // Creates a coroutine scope
launch {
delay(500L)
println("Task from nested launch")
}
delay(100L)
println("Task from coroutine scope") // This line will be printed before the nested launch
}
println("Coroutine scope is over") // This line is not printed until the nested launch completes
}
结果是这样的:
协程范围内的任务
来自 runBlocking 的任务
来自嵌套启动的任务
协程作用域结束
你能解释一下为什么第 20 行的输出 (println("Coroutine scope is over")) 出现在 coroutineScope{} 主体完成后的最后吗?
我只是想,第 20 行在 主线程 上运行,而 launch{} 和 coroutineScope{} 创建的协程正在运行在平行下。所以我预料到了
协程作用域结束
在开头显示。
【问题讨论】: