package unsafe;import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.UUID;import java.util.concurrent.CopyOnWriteArrayList;//java.util.COncurrentModificationException 并发修改异常publicclassListTest{publicstaticvoidmain(String[] args){//并发下Arraylist不安全/*
解决方法:1. List<Object> list = new Vector<>();
2.List<String> list = Collections.synchronizedList(new ArrayList<>());
3.List<String> list = new CopyOnWriteArrayList<>();
*///CopyOfWrite 写入时复制 COW 计算机程序领域的一种优化策略//多个线程使用的时候,list,读取的时候,固定的,写入(覆盖)//在写入的时候避免覆盖,造成数据问题//读写分离//new CopyOnWriteArrayList比Vector牛逼在哪里
List<String> list =newCopyOnWriteArrayList<>();for(int i=0;i<30;i++){newThread(()->{
list.add(UUID.randomUUID().toString().substring(0,5));
System.out.println(list);},String.valueOf(i)).start();}}}
CopyOnWriteArraySet
package unsafe;import java.util.Collections;import java.util.HashSet;import java.util.Set;import java.util.UUID;import java.util.concurrent.CopyOnWriteArraySet;/*
同理可证java.util.COncurrentModificationException 并发修改异常
*/publicclassSetTest{publicstaticvoidmain(String[] args){//HashSet<String> set = new HashSet<>();//解决方案1Set<String> set = Collections.synchronizedSet(new HashSet<>());
Set<String> set =newCopyOnWriteArraySet<>();//hashset底层hashmap,本质就是hashmap的keyfor(int i =0; i <300; i++){newThread(()->{
set.add(UUID.randomUUID().toString().substring(0,5));
System.out.println(set);},String.valueOf(i)).start();}}}