我想用不同线程的结果更新列表。
mainFunction(): List<A> {
var x: List<A> = listOf<A>()
val job = ArrayList<Job>()
val ans = mainScope.async {
var i = 0
for (j in (0..5)) {
job.add(
launch {
val res = async {
func1()
}
x += res.await()
}
)
}
job.joinAll()
}
ans.await()
return x
}
fun func1(): List<A> {
//Perform some operation to get list abc
var abc: List<A> = listOf<A>()
delay(1000)
return abc
}
Run Code Online (Sandbox Code Playgroud)
列表“x”未正确更新。有时,它会附加“res”..有时则不会。有没有线程安全的方法来修改这样的列表?
新的实施:
mainFunction(): List<A> {
var x: List<A> = listOf<A>()
val …Run Code Online (Sandbox Code Playgroud)