集合类不安全
1.ArrayList
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
//ConcurrentModificationException并发修改异常
public class ListTest {
public static void main(String[] args) {
//并发下ArrayList安全吗?
/**
* 解决方案
* 1.List<String> list=new Vector<>(); Vector的add方法底层使用的是Synchronized
* 2.List<String> list= Collections.synchronizedList(new ArrayList<>());
* 3.List<String> list=new CopyOnWriteArrayList<>(); CopyOnWriteArrayList的add方法底层使用的是Lock,效率更高
*/
/**
* CopyOnWrite写入时复制,COW 计算机程序设计领域的一种优化策略
*/
//List<String> list=new Vector<>();
//List<String> list= Collections.synchronizedList(new ArrayList<>());
List<String> list=new CopyOnWriteArrayList<>();
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();
}
}
}
2.HashSet
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;
//ConcurrentModificationException:并发修改异常
public class HashSetTest {
public static void main(String[] args) {
//HashSet<String> set = new HashSet<>();
/**
*解决方案:
* 1.Set<String> set= Collections.synchronizedSet(new HashSet<>());
* 2.Set<String> set=new CopyOnWriteArraySet<>();
*/
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();
}
}
}
3.HashMap
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
//ConcurrentModificationException:并发修改异常
public class HashMapTest {
public static void main(String[] args) {
//线程不安全
//Map<String,String> map=new HashMap<>();
Map<String,String> map= new ConcurrentHashMap<>();
for (int i = 0; i < 30; i++) {
new Thread(()->{
map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0,5));
System.out.println(map);
},String.valueOf(i)).start();
}
}
}