在迭代线程中的列表之前,您可以使用java.util.concurrent.CopyOnWriteArrayList或复制(或使用Collection.toArray方法获取数组).
除此之外,在for-each构造中删除会破坏迭代器,因此在这种情况下处理列表不是一种有效的方法.
但是你可以做到以下几点:
for (Iterator i = list.iterator(); i.hasNext();) {
SomeClass next = i.next();
if (need_to_remove){
i.remove(i);
}
}
要么
for (int i = list.size() - 1; i >= 0; i--){
if (need_to_remove) {
list.remove(i);
}
}
另请注意,如果您的代码从不同的线程访问列表并且修改了列表,则需要同步它.例如:
private final ReadWriteLock lock = new ReentrantReadWriteLock();
final Lock w = lock.writeLock();
w.lock();
try {
// modifications of the list
} finally {
w.unlock();
}
.................................
final Lock r = lock.readLock();
r.lock();
try {
// read-only operations on the list
// e.g. copy it to an array
} finally {
r.unlock();
}
// and iterate outside the lock
但请注意,具有锁定的操作应尽可能短.