我需要帮助来了解以下2条代码的结果
第一个代码段
fun main() = runBlocking {
launch {
println("Task from runBlocking")
}
coroutineScope {
launch {
println("Task from nested launch")
}
println("Task from coroutine scope")
}
println("Coroutine scope is over")
}
第二段代码
fun main() = runBlocking {
launch {
println("Task from runBlocking")
}
println("Coroutine scope is over")
}
第一个代码段的结果是:
Task from coroutine scope
Task from runBlocking
Task from nested launch
Coroutine scope is over
第二个代码段的结果是:
Coroutine scope is over
Task from runBlocking
所以,问题是为什么报表按该顺序打印?
答案 0 :(得分:2)
对于1st snippet
,您使用的是coroutineScope
,正如您从documentation所看到的,它被定义为suspend
函数,因此它阻塞了当前线程,并且{在"Coroutine scope is over"
块完成之前,不会打印{1}}。
对于coroutineScope
,字符串2nd snippet
在"Coroutine scope is over"
之前打印,因为其println在主线程中执行,并且在工作线程中运行的"Task from run blocking"
尚未完成尚未完成。
launch
希望这很有意义:)
答案 1 :(得分:0)
调用 launch
只是将一个任务放在队列中,而调用 coroutineScope
会挂起当前协程,直到新的 coroutineScope 完成。
这就是代码片段 2 中发生的事情:
将“来自 runBlocking 的任务”放入队列
打印“协程范围结束”
从队列中执行唯一的任务(打印“Task from runBlocking”)
这就是代码片段 1 中发生的事情