【发布时间】:2021-06-13 18:54:06
【问题描述】:
在一个用 Kotlin 编写的 Android 项目中,我有一个数据结构,我想在单个线程上执行一些操作,因为两者都不是线程安全的,并且在它上执行的操作顺序很重要。我不希望那个线程成为主线程,因为操作很慢。
我尝试过多种方式创建我的 threadContext:
val threadContext = newFixedThreadPoolContext(1, "Background")
val threadContext = newSingleThreadContext("BioStackContext")
val threadContext = Executors.newSingleThreadExecutor().asCoroutineDispatcher()
每次调用 run 时,我都会得到 isCurrent == true:
threadContext.run {
val isCurrent = Looper.getMainLooper().isCurrentThread()
但是,如果我对其调用 runBlocking,我会得到 isCurrent == false:
runBlocking(threadContext) {
val isCurrent = Looper.getMainLooper().isCurrentThread()
如何在后台非阻塞地运行它?
【问题讨论】:
-
为什么不用协程?
标签: android multithreading kotlin background