协程:`GlobalScope.launch{..}` 中的非阻塞代码在 Kotlin Playgrond 站点上无法按预期工作

问题描述

我有几行代码
案例 1:

 GlobalScope.launch {
       delay(1000L)
       println("world")
 }
 println("hello")
 runBlocking {
      delay(2000L)
 }
 // or I can use
 Thread.sleep(2000L)

结果将是:

hello
world

情况 2: 如果我删除 runBlocking{...} 块或 Thread.sleep(2000L),或更改延迟时间

hello

案例 3: 如果我改变延迟时间 800L

world hello  // without newline character after "world" but include a space character. 

好奇怪!
我不明白为什么会导致这个结果。在情况 2 中,如果 runBlocking{...} 块或 Thread.sleep(2000L) 被省略,协程不执行?需要阻塞代码 runBlocking{..} 块或 Thread.sleep(2000L) 才能执行非阻塞代码 GlobalScope.launch{...}?我正在使用 https://play.kotlinlang.org/ 工具来运行代码

解决方法

检查代码如下:

fun main() {
runBlocking { // this: CoroutineScope
    launch { // launch a new coroutine and continue
        delay(1000L) // non-blocking delay for 1 second (default time unit is ms)
        println("World!") // print after delay
    }
    println("Hello") // main coroutine continues while a previous one is delayed

    launch {
        delay(2000L)
        println("Kotlin")
    }
}

}

结果将是:

Hello
World!
Kotlin