我有2个位于Main类中的内部线程类。有时当一个线程添加新元素,另一个线程却在删除元素时会导致ConcurrentModificationException异常。我认为我不知道如何使它们同步。
Class Main{
HashSet<MyObject> set;
Thread A{
run(running){
...
set.add(obj);
...
}
}
Thread B{
run(){
while (running) {
for (Iterator<MyObject> i = set.iterator(); i.hasNext();) {
MyObject obj= i.next();
if (!obj.isSmt()) {
i.remove();
...
}
}
}
}
}
}
synchronized(set) { ... }
。 - Andreas