JUC:6_1集合类并发问题、集合类并发不安全解决方案1:list
集合类很多都是并发不安全的
ArrayList(始于jdk1.2)是线程不安全的,有几率会报java.util.ConcurrentModificationExceptio 解决方案?
- 1.Vector替换ArrayList
- 2.Collections(集合工具类)提供的将不安全的类转换为安全的类的方法
- 3.JUC提供的读写安全集合类:CopyOnWriteArrayList
集合类并发不安全解决方案1:list
package juc.list;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
public class Test {
public static void main(String[] args) {
List<String> list = new CopyOnWriteArrayList<>();
for (int i = 0; i < 10; i++) {
new Thread(() -> {
list.add(UUID.randomUUID().toString().substring(0, 8));
System.out.println(Thread.currentThread().getName() + "==>" + list);
}, "线程执行" + i).start();
}
}
}
报错
线程执行0==>[959cbe27, f79bb4cf]
线程执行5==>[959cbe27, f79bb4cf, 3557d56c, 9f4fbab2, 16a682a1, dab5ac15, 8d4b295d, 887d8ddd]
线程执行9==>[959cbe27, f79bb4cf, 3557d56c, 9f4fbab2, 16a682a1, dab5ac15, 8d4b295d]
线程执行6==>[959cbe27, f79bb4cf, 3557d56c, 9f4fbab2, 16a682a1, dab5ac15]
线程执行7==>[959cbe27, f79bb4cf, 3557d56c]
线程执行2==>[959cbe27, f79bb4cf, 3557d56c, 9f4fbab2, 16a682a1]
线程执行4==>[959cbe27, f79bb4cf]
线程执行8==>[959cbe27, f79bb4cf, 3557d56c, 9f4fbab2, 16a682a1, dab5ac15, 8d4b295d, 887d8ddd, a8dc1b66, 8d583264]
线程执行3==>[959cbe27, f79bb4cf, 3557d56c, 9f4fbab2, 16a682a1, dab5ac15, 8d4b295d, 887d8ddd, a8dc1b66]
Exception in thread "线程执行1" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:911)
at java.util.ArrayList$Itr.next(ArrayList.java:861)
at java.util.AbstractCollection.toString(AbstractCollection.java:461)
at java.lang.String.valueOf(String.java:2994)
at java.lang.StringBuilder.append(StringBuilder.java:131)
at juc.list.Test.lambda$main$0(Test.java:30)
at java.lang.Thread.run(Thread.java:748)
|