package com.yanxizhu;
import java.util.*;
/**
* @description: synchronizedList遍历错误
* @date: 2022/3/19 11:30
* @version: 1.0
*/
public class ConCurrentHashMapTest {
public static void main(String[] args) {
conCurrentDemo conCurrentDemo = new conCurrentDemo();
for(int i=0;i<5;i++){
new Thread(conCurrentDemo).start();
}
}
public static class conCurrentDemo implements Runnable{
//并发线程安全,修改报错
private static List<String> list = Collections.synchronizedList(new ArrayList<>());
static {
list.add("apple");
list.add("xiaomi");
list.add("huawei");
}
@Override
public void run() {
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
list.add("iphone");
}
}
}
}
线程安全报错:
Exception in thread "Thread-0" Exception in thread "Thread-3" Exception in thread "Thread-4" Exception in thread "Thread-2" Exception in thread "Thread-1" java.util.ConcurrentModificationException
at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1043)
at java.base/java.util.ArrayList$Itr.next(ArrayList.java:997)
at com.yanxizhu.ConCurrentHashMapTest$conCurrentDemo.run(ConCurrentHashMapTest.java:35)
at java.base/java.lang.Thread.run(Thread.java:834)
java.util.ConcurrentModificationException
at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1043)
at java.base/java.util.ArrayList$Itr.next(ArrayList.java:997)
at com.yanxizhu.ConCurrentHashMapTest$conCurrentDemo.run(ConCurrentHashMapTest.java:35)
at java.base/java.lang.Thread.run(Thread.java:834)
通过用CopyOnWriteArrayList修改:
package com.yanxizhu;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* @description: CopyOnWriteArrayList遍历集合
* @date: 2022/3/19 11:30
* @version: 1.0
*/
public class ConCurrentHashMapTest {
public static void main(String[] args) {
conCurrentDemo conCurrentDemo = new conCurrentDemo();
for(int i=0;i<5;i++){
new Thread(conCurrentDemo).start();
}
}
public static class conCurrentDemo implements Runnable{
//并发线程安全,修改报错
// private static List<String> list = Collections.synchronizedList(new ArrayList<>());
private static CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
static {
list.add("apple");
list.add("xiaomi");
list.add("huawei");
}
@Override
public void run() {
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
//CopyOnWriteArrayList,每次会重新复制一个新的,添加。
list.add("iphone");
}
}
}
}
评论 (0)