runBlocking Coroutine 不会阻止 GlobalScope.launch (?)

cub*_*nux 7 kotlin kotlin-coroutines

Kotlin 的 runBlocking Coroutine 应该阻塞当前线程,直到块内的 Coroutine 完成执行,但当块内的 Coroutine 为 GlobalScope.launch 时,它似乎不会这样做

我试图了解 Kotlin 的协程如何工作并阅读此处的文档 - https://kotlinlang.org/docs/reference/coroutines/basics.html

在示例中 -

fun main() = runBlocking<Unit> { // start main coroutine
    GlobalScope.launch { // launch new coroutine in background and continue
        delay(1000L)
        println("World!")
    }
    println("Hello,") // main coroutine continues here immediately
    delay(2000L)      // delaying for 2 seconds to keep JVM alive
}
Run Code Online (Sandbox Code Playgroud)

提到“调用 runBlocking 的主线程会阻塞,直到 runBlocking 内的协程完成”。如果是这样,那么为什么我们需要两秒的延迟来在 runBlocking 结束时阻塞主线程呢?为什么 runBlocking 不会阻塞主线程直到 GlobalScope.launch 完成?

但是,以下内部 runBlocking 会阻塞主线程,直到延迟函数完成。这里有什么区别?为什么上面的 runBlocking 不会阻塞主线程,直到 GlobalScope.launch 以类似的方式完成 -

fun main(){ // start main coroutine
    GlobalScope.launch { // launch new coroutine in background and continue
        delay(1000L)
        println("World!")
    }
    println("Hello,") // main coroutine continues here immediately
    runBlocking{
     delay(2000L)      // delaying for 2 seconds to keep JVM alive
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望当主函数包装在 runBlocking 协同例程中时,主线程应该被阻塞,直到 GlobalScope.launch 完成其执行。

Mat*_*247 7

作用域中的协程将阻塞,直到job同一作用域中的所有子协程完成为止。然而,在另一个作用域中显式启动协程不会使它们成为真正的子协程,因此不会等待它们。

本文还提供了有关此特定案例的一些信息: https: //medium.com/@elizarov/the-reason-to-avoid-globalscope-835337445abc