sách gpt4 ai đã đi

Giải quyết ConcurrentModificationException

In lại 作者:行者123 更新时间:2023-11-30 09:40:54 29 4
mua khóa gpt4 Nike

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

công khai void run() {
int stepCount = 0;
int dx;
int dy;
while (m_threadTrap){
dx = 0;
dy = 0;

synchronized (m_circles) {
for (Iterator 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。

以及以下主题:

công khai void run() {
while (m_threadTrap){
int topPosition;
int bottomPosition;
int leftPosition;
int rightPosition;
ArrayList removedCircles = new ArrayList();
synchronized (m_circles.getCircles()) {
for (Iterator 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对象。
他们都没有为我解决。

1 Câu trả lời

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

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

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

29 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com