[英]CoroutineScope Questions
在 Coroutine Scope 上,为什么先调用 launch 块时先调用最后一个 println()?
海杰·布赖恩·李,
在runBlocking
中,您可以在调用launch{}
时启动两个新的协程,而不会阻塞当前线程。 所以runBlocking
中的块继续执行并且println
s被执行。
如果您希望launch
块首先完成,您必须通过在其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
Launch 是一个协程构建器。 它与其余代码同时启动一个新的协程,该协程继续独立工作。 这就是为什么首先执行和打印外部代码的原因。
尝试使用 coroutineScope 的挂起功能
使用挂起功能
参考这里。 在 kotlin 文档中提到https://kotlinlang.org/docs/coroutines-basics.html#scope-builder
fun main() = runBlocking{
doWork()
}
fun doWork() = coroutineScope{
launch{
//your code here
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.