我有一堆從基類啓動的Runnable對象。這些對象隨機遍歷和刪除共享ArrayList中的項目。我已同步這兩種方法,但得到ConcurrentModicationException
。我相信它是因爲they are synchronized but are not synchronized on each other。是這樣嗎?如果是這樣,我會獲得哪個課程的鎖定?由於未同步的同步方法導致ConcurrentModicationException
環境類別:
class Environment{
ArrayList<Critter> critter_array = new ArrayList<Critter>();
ArrayList<Food> food_array = new ArrayList<Food>();
Environment(){
Executor ex = Executors.newCachedThreadPool();
Critter A = new Critter();
Critter B = new Critter();
critter_array.add(A);
critter_array.add(B);
ex.execute(A);
ex.execute(B);
}
public synchronized void destroyFood(Food item){
Iterator<Food> iter = food_array.iterator();
while(iter.hasNext()){
Food temp = iter.next();
food_array.remove(temp);
break;
}
}
}
小動物類:
class Critter implements Runnable{
Environment envi;
Critter(Environment E){
envi = E;
}
@Override
public void run() {
//do other stuff
CritterUtilities.iteratorMethod(this, envi);
}
}
CritterUtilities類:
class CritterUtilities{
public static synchronized iteratorMethod(Critter self, Environment envi){
Iterator<OtherObject> iter = envi.getFood().listIterator();
while(iter.hasNext()){
Food temp = iter.next(); /////////Problem is here
//other stuff that's not related to the prob
}
}
}
堆棧跟蹤:
Exception in thread "pool-1-thread-2" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
at java.util.AbstractList$Itr.next(Unknown Source)
at CritterUtil.getViewableFood(CritterUtil.java:28)
at CritterUtil.getNearestFood(CritterUtil.java:41)
at Critter.hunt(Critter.java:163)
at Critter.run(Critter.java:139)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
是的,他們在不同的事情上同步。 – zapl
破壞方法中的「food_list」是什麼? – d0x
@ChristianSchneider我的壞,編輯 – Daniel