runBlocking 协程不会阻塞 GlobalScope.launch (?)

runBlocking Coroutine doesn't block GlobalScope.launch (?)

Kotlin 的 runBlocking 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
}

提到"The main thread, that invokes runBlocking, blocks until the coroutine inside runBlocking completes"。如果是这样那么为什么我们需要两秒的延迟在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
    }
}

我希望当 main 函数被包裹在 runBlocking 协程中时,主线程应该被阻塞直到 GlobalScope.launch 完成它的执行。

作用域中的协程将阻塞,直到它在同一作用域中的所有子(jobs)完成。但是,在另一个范围内显式启动协程不会使它们成为真正的子程序,因此不会等待它们。

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