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)
}
}