gpt4 book ai didi

java - 解决 ConcurrentModificationException

转载 作者:行者123 更新时间:2023-11-30 09:40:54 26 4
gpt4 key购买 nike

我正在写一个小游戏,屏幕上有许多圆圈在移动。
我在两个线程中管理圈子,如下所示:

public void run() {
int stepCount = 0;
int dx;
int dy;
while (m_threadTrap){
dx = 0;
dy = 0;

synchronized (m_circles) {
for (Iterator<Circle> it = m_circles.iterator(); it.hasNext();){
Circle c = it.next(); //Exception thrown here.
if (c.getDirX() != 0)
if (stepCount % c.getDirX() == 0){
dx = 1;
}
if (c.getDirY() != 0)
if (stepCount % c.getDirY() == 0){
dy = 1;
}

c.move(dx, dy);
}
}
if (stepCount == 150000){
stepCount = 0;
}
stepCount++;
}
}

圆 ArrayList 中的 m_circles。

以及以下主题:

public void run() {
while (m_threadTrap){
int topPosition;
int bottomPosition;
int leftPosition;
int rightPosition;
ArrayList<Circle> removedCircles = new ArrayList<Circle>();
synchronized (m_circles.getCircles()) {
for (Iterator<Circle> it = m_circles.getCircles().iterator(); it.hasNext();){
Circle c = it.next();

// Some calculation to evaluate which circles should be removed
removedCircles.add(c);
}
}
}
try{
Thread.sleep(25);
}
catch (Exception e) { }

m_circles.getCircles().removeAll(removedCircles);

if (m_circles.getCircles().size() < 30)
m_circles.addNewCircle();

repaint();
}
}

我的问题是我在行中得到了 ConcurrentModificationException

Circle c = it.next();

在第一个线程中。起初我尝试使用 foreach 循环遍历 ArrayList,这给了我同样的异常。
在对这个异常进行了一些研究之后,我看到了两个解决方案:
1. 将访问集合的部分放在同步块(synchronized block)中。
2.使用集合的Iterator对象。
他们都没有为我解决。

最佳答案

要使 synchronized() {} block 有效,对 protected 对象的所有访问 都必须包装在同步块(synchronized block)中。您可能忘记包装一些访问权限。

另一个“陷阱”是 ConcurrentModificationException 也可能意味着它被并发修改在同一个线程。例如,如果您在遍历集合时从集合中移除一个元素,则可能会出现此异常。 (作为异常(exception),您可以通过迭代器本身安全地删除元素)

关于java - 解决 ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9224821/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com