微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决协程:`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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。