我正在使用以下课程:
public class Ticker implements Runnable {
private LinkedList<Timeable> timeables = new LinkedList<>();
@Override
public void run() {
ListIterator<Timeable> it = timeables.listIterator();
while (it.hasNext()) {
it.next().tick();
}
}
public void add(Timeable timeable) {
timeables.add(timeable);
}
public void remove(Timeable timeable) {
timeables.remove(timeable);
}
}
我认为迭代器会阻止ConcurrentModificationException,但会在“it.next()。tick();”中抛出一个。
我该如何解决这个问题?
答案 0 :(得分:0)
java集合类是快速失败的,因此LinkedList
如果其结构被一个线程修改而另一个线程正在迭代其元素,则会抛出ConcurrentModificationException
。
对于多线程代码,您应该使用线程安全集合,例如CopyOnWriteArrayList
(在某个时间点提供集合的故障安全迭代器)或ConcurrentLinkedDeque
(如果您只需要访问第一个或最后一个元素)。