Kotlin Coroutine输出理解困难

问题描述 投票:0回答:0
fun main() {
    println("Start of program")
    GlobalScope.launch{

        println("Starting coroutine")
        val result = someOperation()
        println("Coroutine Running thread is: ${Thread.currentThread().name}")
        println("Coroutine completed with result: $result")
        println("End of the coroutine function")

    }
    println("End of program")
}

suspend fun someOperation(): String { //This is a coroutine now (Due to suspend modifier).
    delay(3000) // long-running operation
    return "Operation performed successfully"
}

有人能解释一下为什么我得到这个作为我的输出吗?

Start of program
End of program

而预期的输出是:

Start of program
Starting coroutine
Coroutine Running thread is: DefaultDispatcher-worker-1
Coroutine completed with result: Operation performed successfully
End of the coroutine function
End of program

如果协程要在后台线程上运行,为什么协程在上述情况下甚至没有被调用?

根据我的说法,主函数应该首先被触发,它应该产生协程(最终是线程)并且至少在完成主函数之后,程序应该让协程在退出之前完成。

附言: 我在协同程序和异步编程方面苦苦挣扎。如果有人有相同的好资源,请分享它会有所帮助。

kotlin asynchronous kotlin-coroutines coroutine
© www.soinside.com 2019 - 2024. All rights reserved.