我正在寫一個有許多圈子在屏幕上移動的小遊戲。
我在管理兩個線程圓如下:
解決ConcurrentModificationException
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++;
}
}
m_circles在圓的ArrayList。
而以下主題:
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();
}
}
我的問題是,我在第一線的線
Circle c = it.next();
得到ConcurrentModificationException的。起初我試着用foreach循環來檢查ArrayList,這給了我同樣的例外。
在研究了這個例外之後,我看到了兩個解決方案:
1.將訪問集合的部分放入同步塊中。
2.使用集合的Iterator對象。
他們都沒有爲我解決它。
非常感謝你,確實有兩個線程是我忘記包裝的另一個接入點。 – Nadavrbn 2012-02-10 08:44:06