在Kotlin指南这里中,当解释runBlocking和coroutineScope之间的区别时,它说:
..。主要的区别是runBlocking方法阻塞当前线程等待,而coroutineScope只是挂起,释放底层线程用于其他用途。..。
这是可以理解的但是,在这里列出的示例代码中:
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
}它产生以下输出:
Task from coroutine scope
Task from runBlocking
Task from nested launch
Coroutine scope is over将coroutineScope替换为runBlocking:
import kotlinx.coroutines.*
fun main() = runBlocking { // this: CoroutineScope
launch {
delay(200L)
println("Task from runBlocking")
}
runBlocking { // instead of coroutineScope, previously
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将阻塞直到它的块完成,包括所有子协同:
Task from coroutine scope
Task from nested launch
Task from runBlocking
Coroutine scope is over有人能解释一下这种行为吗?我在这里监督什么?
发布于 2021-02-27 15:44:07
在runBlocking中拥有runBlocking是..。不寻常。更常见的是,runBlocking仅仅是一种外在的东西。实际上,runBlocking的实现将使用外部runBlocking的事件循环,而不是创建新的事件循环,因此在这种情况下,它实际上就像coroutineScope一样。
发布于 2021-02-27 15:28:22
runBlocking只阻塞当前线程,直到block返回为止。它不影响block的执行方式。
https://stackoverflow.com/questions/66400241
复制相似问题