Kotlin 协程挂起延续线程

问题描述 投票:0回答:1

我试图了解协程在幕后是如何工作的。我有这个简单的代码,可以挂起协程并在不同的线程中恢复它。

fun main(){
    fun pt(msg : String){
        println("${Thread.currentThread().name}: ${msg}")
    }
    suspend fun a(){
        pt("A")
        suspendCoroutine { cont ->
            thread (name = "new thread") {
                pt("resuming")
                cont.resume(Unit)
            }
        }
        pt("B")
    }
    runBlocking {
        a()
    }
}

由于协程在

new thread
中恢复,我本以为B的打印也是由这个线程完成的,但似乎并非如此。

main: A
new thread: resuming
main: B

有人能解释一下发生了什么事吗?是启动延续对象的协程部分并且

resume
调用将执行传递给它的原始线程吗?

kotlin coroutine suspend
1个回答
0
投票

您不会在新线程中恢复。您正在使用新线程在协程挂起时执行某些操作(打印“恢复”)并指示协程然后恢复。然后这条线就完成了。这不是让线程执行协程工作的方式。调度程序负责将协程工作块分配给线程。

© www.soinside.com 2019 - 2024. All rights reserved.