我有下面的代碼片段代碼。我有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(;;)語句,對吧? –