繁体   English   中英

CoroutineScope 问题

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM