。由於收藏的內部狀態變得不一致,因此出現了此例外。 ConcurrentModificationException
>
<code class="language-java">Exception in thread "main" java.util.ConcurrentModificationException at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:000) at java.base/java.util.ArrayList$Itr.next(ArrayList.java:000) at com.journaldev.ConcurrentModificationException.ConcurrentModificationExceptionExample.main(ConcurrentModificationExceptionExample.java:00)</code>在以下情況下發生此例外:
在迭代過程中進行
modCount
用於復制異常的此算法演示瞭如何在Java中觸發a:
ConcurrentModificationException
ArrayList
>人口:ArrayList
>使用list.iterator()
(例如,添加或刪除元素)。
ArrayList
ConcurrentModificationException
>
,因為在迭代器遍歷它時修改了列表。
<code class="language-java">import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ConcurrentModificationExample { public static void main(String[] args) { List<integer> myList = new ArrayList<>(); myList.add(1); myList.add(2); myList.add(3); Iterator<integer> iterator = myList.iterator(); while (iterator.hasNext()) { Integer value = iterator.next(); System.out.println("Value: " + value); if (value == 2) { myList.remove(value); // Modification during iteration! } } } }</integer></integer></code>安全修改技術
ConcurrentModificationException
myList.remove(value)
避免這種例外,請使用以下方法:
:
複製列表:Iterator.remove()
在迭代之前創建列表的副本並修改副本。
iterator.remove()
>或>。
將迭代和修改包裝在同步塊中,以確保線程安全。 >
CopyOnWriteArrayList
ConcurrentHashMap
安全去除安全 此修訂的代碼可以安全地刪除元素,而無需拋出異常。 請記住根據您的特定需求和並發要求選擇適當的技術。 對於多線程方案,使用並發集合通常是首選。
>以上是在Java中使用迭代器時conturrentModification Exception的詳細內容。更多資訊請關注PHP中文網其他相關文章!