kotlin - 为什么协程首先在调用者线程上运行,但在第一个挂起点之后它在 “Dispatchers.Unconfined” 中的 DefaultExecutor 上运行?

标签 kotlin kotlin-coroutines

下面的代码打印

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/

相关文章:

android - 当我尝试从中获取数据时,ViewModel 返回清晰的对象

android - Gradle kotlin 不支持的方法 Dependencies.getAtoms()

kotlin - 给定范围内的安全异步

android - 使用 launch() 范围时无法为 LiveData 变量赋值,但可以使用 runBlocking() 为 LiveData 赋值

kotlin - 链 kotlin 流取决于结果状态

android - 为什么 ViewModel 和 Fragment 中的相同变量不同?

kotlin - 将 Kotlin JavaScript 代码拆分为多个 maven 模块

android - Twitter API 401 位于/account/verify_credentials

android - emit 和 emitSource 与 LiveData 之间有什么区别? (如实时用例)

kotlin - 如何使用超时值同步调用异步请求?