下面的代码打印
import kotlinx.coroutines.*
fun main() = runBlocking<Unit> {
launch(Dispatchers.Unconfined) {
// not confined -- will work with main thread
println("thread ${Thread.currentThread().name}")
delay(500)
println("thread ${Thread.currentThread().name}")
}
}
第一次在调用者线程上运行,但在第一个挂起点之后,它在“Dispatchers.Unconfined”中的 DefaultExecutor 上运行
thread main
thread kotlinx.coroutines.DefaultExecutor
最佳答案
阅读Dispatchers.Unconfined
的描述,它准确地解释了这种行为:
A coroutine dispatcher that is not confined to any specific thread. It executes initial continuation of the coroutine immediately in the current call-frame and lets the coroutine resume in whatever thread that is used by the corresponding suspending function, without mandating any specific threading policy. Note: use with extreme caution, not for general code.
关于kotlin - 为什么协程首先在调用者线程上运行,但在第一个挂起点之后它在 “Dispatchers.Unconfined” 中的 DefaultExecutor 上运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54695301/