kotlin: 为协程自定义线程池

一,代码:

自定义dispatcher:

自定义了两个dispatcher

val myCustomDispatcher1 = newSingleThreadContext("MyCustomThread1")
val myCustomDispatcher2= Executors.newSingleThreadExecutor{ r -> Thread(r, "MyCustomThread2") }.asCoroutineDispatcher()

函数:

//得到用户信息,演示指定dispatcher
suspend fun getUserInfo(): String {
    logX("Before IO Context.")
    withContext(Dispatchers.IO) {
        logX("In IO Context.")
        delay(1000L)
    }
    logX("After IO Context.")
    return "BoyCoder"
}

调用:

        //处理按钮点击事件
        binding.button1.setOnClickListener {
            runBlocking(myCustomDispatcher2) {
                val user = getUserInfo()
                logX(user)
            }
        }

二,测试效果:

posted @ 2025-08-02 15:00  刘宏缔的架构森林  阅读(31)  评论(0)    收藏  举报