为什么这段协程代码不打印任何内容?

new*_*der 2 kotlin kotlin-coroutines

当使用 runBlocking 时,会打印行,但在以下情况下不会打印任何内容

fun main(){
     GlobalScope.launch{
    
        println("function started") //printing the first line
        delay(1000)
        println("function ended")   //printing the last line

}}
Run Code Online (Sandbox Code Playgroud)

Jof*_*rey 5

您的程序在启动的协程有机会启动之前终止。

launch启动一段异步代码,因此程序可以在调用后继续运行,launch而无需等待 的主体launch执行。当前代码中没有任何内容会等待该协程完成后再终止程序,因此程序就结束了。

当使用 runBlocking 时,会打印这些行

我假设您指的是这样运行它:

fun main(): Unit = runBlocking { // this: CoroutineScope
    launch {
        println("function started") //printing the first line
        delay(1000)
        println("function ended")   //printing the last line
    }
}
Run Code Online (Sandbox Code Playgroud)

runBlocking这里定义了lambda 内部CoroutineScope可用的a 。thisHerelaunch是在该范围内启动的,这使其成为 的子协程runBlocking。

根据定义,runBlocking阻塞当前线程(这里是主线程),直到所有子协程完成。这就是在这种情况下程序等待协程完成的原因。

如果您刚刚学习协程,那么您确实应该避免使用像GlobalScope. 相反,尝试坚持结构化并发。结构化并发是一种通过父子关系构建协程的方法,这样您就不会因协程泄漏而感到惊讶(就像这个)。