我正在研究协同疗法,并写了一些例子,我发现了一些奇怪的东西。即使我首先编写了launch构建,它的启动也比coroutineScope晚。我知道coroutineScope有一个悬念点。有没有人解释过这件事?
下面是我的代码
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
println("Start")
}
coroutineScope {
launch {
delay(1000)
println("World!")
}
println("Hello")
}
println("Done")
/*
expected
Start
Hello
World!
Done
result
Hello
Start
World!
Done
*/
}发布于 2022-11-14 03:48:56
launch块不会立即执行。它被安排为异步执行,并且函数会立即返回。这就是为什么没有立即打印"Start“并且控件在coroutineScope中移动的原因。您可以使用一个简单的示例来验证这一点,如:
launch {
println("Start")
}
println("End")这里您将看到End是在Start之前打印的。
https://stackoverflow.com/questions/74426576
复制相似问题