[英]Synchronise function inside GlobalScope.launch(Main): Kotlin
Scenerio: let fun A()
and fun B()
be two functions. Scenerio:让
fun A()
和fun B()
成为两个函数。 Inside A()
we are calling B(
).在
A()
我们调用B(
)。 B()
execution time takes around 5sec and meanwhile some other thread call A() again, then I am getting ConcurrentModificationException
. 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
}
How to synchronise it so that at a time one thread can execute B().如何同步它以便一次一个线程可以执行 B()。 I already tried to use
@synchronise
.我已经尝试使用
@synchronise
。 As im new in kotlin, Please suggest.由于我是 kotlin 的新手,请提出建议。
Problem seems to be exist in fun B()
, where you might be doing loop in some Collection
type (sa List, Stack...) and also deleting/inserting new element to that Collection type.问题似乎存在于
fun B()
,您可能会在某些Collection
类型(sa 列表、堆栈...)中执行循环,并且还向该集合类型删除/插入新元素。
If that is the case, you should use Iterator
to loop and you can delete/insert items while iterating.如果是这种情况,您应该使用
Iterator
进行循环,并且您可以在迭代时删除/插入项目。 But if one thread is looping and other thread is inserting/deleting items, you need to synchronize access to that Collection type (using @Synchronized fun B()
etc...).但是如果一个线程在循环而另一个线程正在插入/删除项目,则需要同步对该集合类型的访问(使用
@Synchronized fun B()
等...)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.