//java.util.ConcurrentModificationException并发修改异常
public class ListTest {
public static void main(String[] args) {
//解决方案一:并发下ArrayList是不安全的 Vector是安全的
//解决方案二:List<String> list= Collections.synchronizedList(new ArrayList<>());
//解决方案三:List<String> list=new CopyOnWriteArrayList<>();在每次add(也就是写入之前)都会创建一个比原来数组大一的复制数组
List<String> list=new ArrayList<>();
for (int i = 0; i <= 10; i++) {
new Thread(()->{
list.add(UUID.randomUUID().toString().substring(0,5));
System.out.println(list);
},String.valueOf(i)).start();
}
}
}
//java.util.ConcurrentModificationException并发修改异常
public class SetTest {
public static void main(String[] args) {
Set<String> set=new HashSet<>();
//方法一:Set<String> set=Collections.synchronizedSet(new HashSet<>());
//方法二:Set<String> set=new CopyOnWriteArraySet<>()
for (int i = 0; i <= 30; i++) {
new Thread(()->{
set.add(UUID.randomUUID().toString().substring(0,5));
System.out.println(set);
},String.valueOf(i)).start();
}
}
}
HashSet的底层是什么
底层就是HashMap add方法就是map.add 因为map的key是无法重复的
![](https://i-blog.csdnimg.cn/blog_migrate/eb7394cae776c70d86626a218c5cad42.png)
//java.util.ConcurrentModificationException
public class MapTest {
public static void main(String[] args) {
//负载因子默认 0.75
//初始化容量默认 16
//实际容量:16*0.75
//解决方案一: Map<String,String> map=Collections.synchronizedMap(new HashMap<>());
//解决方案二: Map<String,String> map=new ConcurrentHashMap<>();
Map<String,String> map=new HashMap<>();
for (int i = 0; i <= 20; i++) {
new Thread(()->{
map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0,5));
System.out.println(map);
},String.valueOf(i)).start();
}
}
}