在Coroutine范围内,当启动块首先被调用时,为什么最后一个println()首先被调用?


发布于 2022-05-13 04:01:53
Hej BrianLee
在runBlocking中,在调用launch{}时启动两个新的协同线程而不阻塞当前线程。因此,runBlocking内部的块继续运行,并且执行println。
如果您想让launch-blocks首先完成,则必须让线程在其Job上使用.join()等待其执行。
runBlocking {
val job = launch {
println("launch : ${Thread.currentThread() .name}")
println("launch 1")
}
job.join()
println("runBlocking: ${Thread. currentThread () .name}")
println("runBlockging")
}链接:https://kotlinlang.org/docs/coroutines-basics.html#an-explicit-job
发布于 2022-05-13 03:52:44
发射是一个协同系统的建设者。它与代码的其余部分同时启动一个新的协同机制,该代码继续独立工作。这就是为什么首先执行和打印外部代码的原因。
使用 coroutineScope尝试挂起函数
使用挂起函数
这里是
参考资料。在kotlin docs https://kotlinlang.org/docs/coroutines-basics.html#scope-builder中提到
fun main() = runBlocking{
doWork()
}
fun doWork() = coroutineScope{
launch{
//your code here
}
}https://stackoverflow.com/questions/72223696
复制相似问题