在这种Kotlin Coroutines情况下的主线程之前,为什么Coroutine在后台执行?

发布于 2025-01-22 05:14:51 字数 1160 浏览 1 评论 0原文

我是Kotlin Coroutines的新手,并试图了解Coroutine Builder 启动,该在后台启动了Coroutine,并且不会阻止主线程。因此,我以这样的简单示例对其进行了测试。

fun main() {
    GlobalScope.launch {
        delay(1000L)
        println("World!")
    }
    println("Hello!")
    runBlocking {
        delay(2000L) // Testing by modifying this delay time
    }
}

对于我的知识,因为背景coroutine有1秒的延迟,同时,主线程中的println(“ hello!”)将首先立即执行。然后,由于我们已经使用delay>在runblocking中阻止了主线程2秒以保持JVM的活力,因此背景Coroutine应该有足够的时间执行(“世界!”)

我已经在到较小的值,例如delay(1001L)delay> delay> delay(700L)然后打印输出:

World! Hello!

延迟时间为1002ms,有时会打印,

Hello!
World!

但有时也会打印

World! Hello!

,我假设,如果Runblocking中的延迟时间为700ms,则只能打印Hello!

我知道,借助足够的JVM活着的时间(例如第一个代码段中的2000毫秒延迟案例),Background Coroutine有足够的时间执行println(“ world!”)。但是,令人困惑的是,有时world!是在hello!之前打印出来的。是什么可能导致这种行为?

I am a newbie to Kotlin coroutines and trying to understand the coroutine builder launch which starts a coroutine in background and does not block the main thread. So I have tested it with a simple example like so.

fun main() {
    GlobalScope.launch {
        delay(1000L)
        println("World!")
    }
    println("Hello!")
    runBlocking {
        delay(2000L) // Testing by modifying this delay time
    }
}

To my understading, because there is a 1 second delay in the background coroutine, in the meantime, the println("Hello!") in the main thread will be executed immediately first. And then, because we have blocked the main thread using delay in runBlocking for 2 seconds to keep the JVM alive, the background coroutine should have enough time to execute println("World!").

I have tested this code on Kotlin Playground, and have tried changing the delay time in runBlocking to smaller values such as delay(1001L) or delay(700L) which then prints the output:

World! Hello!

With delay time of 1002ms, it sometimes prints

Hello!
World!

but sometimes prints

World! Hello!

Also, I assumed that if the delay time in runBlocking is 700ms, then only Hello! should be printed.

I understand that with sufficient time of JVM being alive (such as the 2000ms delay case in the first code snippet), the background coroutine has enough time to execute println("World!"). However, what is confusing is the fact that sometimes World! is printed before Hello! and also on the same line. What could be causing this type of behaviour?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文