【发布时间】:2020-01-30 05:27:18
【问题描述】:
场景:让fun A() 和fun B() 成为两个函数。在A() 内部,我们调用B()。 B() 执行时间大约需要 5 秒,同时其他线程再次调用 A(),然后我得到 ConcurrentModificationException。
fun A(){
GlobalScope.launch(Main) {
val result = withContext(IO) {
B()
}
if (this@activity.isValid()) {
suggestedFeedItems = result
} else {
}
}
}
fun B(){
//some code that takes some time to execute
}
如何同步它,以便一个线程一次可以执行 B()。我已经尝试使用@synchronise。由于我是 kotlin 的新手,请建议。
【问题讨论】:
-
Mutex.withLock?见kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/… -
最好使用
Actor来序列化处理。
标签: android kotlin kotlin-coroutines