在我认为是单线程的情况下,我得到了一个 ConcurrentModificationExeption。我还知道,如果您遍历一个 List 并尝试在循环中修改它,就会出现异常。因此,我实际上使用迭代器对其进行迭代和修改。但是,我仍然有异常(exception)。
基本上,我正在实现一些动画管理器,并将我所有的 IAnimation 对象存储在一个 ArrayList 中。有一种更改列表的公共(public)方法,即 addAnimation。还有另一种循环遍历列表的方法,它是 calculateTick。由于这两种方法都是同步的,我认为我没有线程问题。如前所述,我使用迭代器遍历循环。你们知道为什么我有这个异常(exception)吗?
这是我的代码:
private List<IAnimation> animations = new ArrayList<IAnimation>();
public synchronized void addAnimation(IAnimation animation) {
animations.add(animation);
mLooper.update();
inAnimation = true;
}
public synchronized void calculateTick(float tpf) {
for (Iterator<IAnimation> iterator = animations.iterator(); iterator.hasNext();) {
IAnimation animation= iterator.next();
boolean animateMore = animation.calculateTick(tpf);
if (!animateMore ) {{
iterator.remove();
}
}
}
这是我的异常(exception):
E/AndroidHarness(9546): Exception thrown in Thread[GLThread 1260,5,main]
04-17 11:55:38.001: E/AndroidHarness(9546): java.util.ConcurrentModificationException 04-17 11:55:38.001:E/AndroidHarness(9546):在 java.util.ArrayList$ArrayListIterator.remove(ArrayList.java:582) 04-17 11:55:38.001:E/AndroidHarness(9546):在 com.avaya.mco.gui.animation.AnimationManager.calculateTick(AnimationManager.java:50) 04-17 11:55:38.001:E/AndroidHarness(9546):在 com.avaya.mco.gui.jmonkey.android.MyApplication.simpleUpdate(MyApplication.java:60) 04-17 11:55:38.001: E/AndroidHarness(9546): 在......
最佳答案
你确定这里没有缺少其他函数来遍历列表吗?也许是播放动画的东西?
此外,如果这没有帮助,请尝试使用“ConcurrentLinkedQueue”: http://developer.android.com/reference/java/util/concurrent/ConcurrentLinkedQueue.html 它适用于所有版本,它说对于迭代器: “...返回的迭代器是一个“弱一致”的迭代器,它永远不会抛出 ConcurrentModificationException,并保证遍历迭代器构造时存在的元素,并且可能(但不保证)反射(reflect)构造后的任何修改。 "
关于android - ConcurrentModificationException 即使在 android ArrayList 中使用 Iterator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10195189/