Kotlin CoroutineScope阻止当前线程
根据Kotlin文档,协同例程不会阻止当前线程。它们显示了以下代码示例:Kotlin CoroutineScope阻止当前线程,kotlin,Kotlin,根据Kotlin文档,协同例程不会阻止当前线程。它们显示了以下代码示例: fun main() = runBlocking { // this: CoroutineScope launch { delay(200L) println("Task from runBlocking") } coroutineScope { // Creates a coroutine scope launch { d
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不会阻止当前线程。那么,为什么在第一次发布完成后不打印这一行呢
println("Coroutine scope is over")
这条线不是协同作用域的一部分。我本以为结果会是:
Coroutine scope is over
Task from runBlocking
Task from coroutine scope
Task from nested launch
这回答了你的问题吗?哇。谢谢。似乎其他人也有同样的问题。这能回答你的问题吗?哇。谢谢。似乎其他人也有同样的问题。