【问题标题】:Solving ConcurrentModificationException problem with Asynctask (ANDROID)使用 Asynctask (ANDROID) 解决 ConcurrentModificationException 问题
【发布时间】:2019-08-20 15:30:42
【问题描述】:

我得到一个 ConcurrentModificationException (ArrayList) 异常,我不知道如何解决它,因为异常非常罕见且不可重现。

情况: 我有一个主线程:

for(Element element : myList){
    Value value = element.getValue(); <-------- ConcurrentModificationException (ArrayList)
}

还有一个 AsyncTask:

public class LoadMapObjectsTask extends AsyncTask<String, String, String> {
    protected String doInBackground(String... params) {
        // some other logic
        myList.remove(element);
    }
}

我可以理解冲突,但我不确定如何正确防止它。也许用简单的同步{}?我该如何解决这个问题?

【问题讨论】:

  • doSomthing() 是否同步运行?
  • 是的。它的简单执行东西没有任何额外的线程。我根据实际情况修改了代码示例。
  • 我建议您使用“帮助列表”,这样您就不会从正在迭代的列表中删除项目。
  • 或者使用迭代器列表

标签: java android multithreading android-asynctask


【解决方案1】:

也许您可以更改代码以返回特定值,该值可被识别为使用Iterator.remove() 删除元素的标志:

Iterator<Element> it = myList.iterator();
while (it.hasNext()) {
  Value value = it.next().getValue()
  if (value == null) {
    it.remove();
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-02
    相关资源
    最近更新 更多