runBlocking 和 coroutineScope 在 Kotlin 协程中有什么区别?
大家好!我开始学习 Kotlin 中的协程,遇到了两个看起来非常相似的函数:runBlocking 和 coroutineScope。我读过文档,但对它们的行为仍然不太清楚。
这是我写的一个例子:
fun main() = runBlocking {
launch {
delay(1000L)
println("World!")
}
println("Hello,")
}
另一个例子:
fun main() = runBlocking {
coroutineScope {
launch {
delay(1000L)
println("World!")
}
println("Hello,")
}
}
两个例子都先输出 "Hello,",一秒钟后输出 "World!"。但我怀疑它们之间存在差异,而且这种差异很重要。区别在哪里?
我特别想知道:
- 为什么
runBlocking会阻塞当前线程,而coroutineScope不会? - 这些函数在实际中如何表现?