併發修改異常
阿新 • • 發佈:2021-10-21
package com.yishan.foreach; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; /** * @Author yishan * @Date 2021/10/19 0019 13:23 * @Version 1.0 */ public class RemoveDemo { //併發修改異常 public static void main(String[] args) { //會產生併發修改異常 //ConcurrentModificationException_for(); //ConcurrentModificationException_iter(); //不會產生併發修改異常 //iteratorRemove(); //CopyOnWriteArrayList(); } /** * CopyOnWriteArrayList 不會產生併發修改異常 */ private static void CopyOnWriteArrayList() { List<String> list = new CopyOnWriteArrayList<>(); for (int i = 0; i < 10; i++) { list.add(i + ""); } System.out.println(list); Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { String str = iterator.next(); if ("5".equals(str)) { list.remove(5); } } System.out.println(list); } /** * iterator.remove()方法可在迭代器遍歷中刪除元素 */ private static void iteratorRemove() { List<String> list = new ArrayList<>(); for (int i = 0; i < 10; i++) { list.add(i + ""); } System.out.println(list); Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { String str = iterator.next(); if ("5".equals(str)) { iterator.remove(); } } System.out.println(list); } /** * 迭代器 */ private static void ConcurrentModificationException_iter() { List<String> list = new ArrayList<>(); for (int i = 0; i < 10; i++) { list.add(i + ""); } System.out.println(list); Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { String str = iterator.next(); if ("5".equals(str)) { list.remove(5); } } System.out.println(list); } /** * 增強for遍歷 */ private static void ConcurrentModificationException_for() { List<String> list = new ArrayList<>(); for (int i = 0; i < 10; i++) { list.add(i + ""); } System.out.println(list); for (String o : list) { if ("5".equals(o)) { list.remove(5); } } System.out.println(list); } }