我有下面的代码片段代码。我有2个线程A和B同时运行。循环中是否存在ConcurrentModificationException异常
List<String> listPeople = new ArrayList<>();
// Add more item
.....
Thread A
for (String item : listPeople) {
System.out.println("Name is: " + item.name);
}
Thread B
- add/remove item to list people
使用这种for循环形式,它通过List的iterator
循环。那么它会崩溃与ConcurrentModificationException
?
正如@Daniel Pryden在他的回答中解释的那样,你不能指望它。有时它可能会抛出ConcurrentModificationException,而有时它可能不会。 –
谢谢你回答。为了安全起见,我应该使用for(;;)语句,对吧? –