5.1、List不安全
package com.chen.unsafe;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
// java.util.ConcurrentModificationException 并发修改异常
public class ListTest {
public static void main(String[] args) {
// 并发下 ArrayList是不安全的
/**
* 解决方案
* 1、List<String> list = new Vector<>();
* 2、List<String> list = Collections.synchronizedList(new ArrayList<>());
* 3、List<String> list = new CopyOnWriteArrayList<>();
*/
// CopyOnWrite 写入时复制 COW 计算机程序设计领域的一种优化策略
// 多个线程调用的时候,list,读取的时候,固定的,写入(覆盖)
// 在写入的时候避免覆盖,造成数据问
// 读写分离
// CopyOnWriteArrayList 比 Vector 好在哪里
List<String> list = new CopyOnWriteArrayList<>();
for (int i = 1; i < 10; i++) {
new Thread(()->{
list.add(UUID.randomUUID().toString().substring(0,5));
System.out.println(list);
},String.valueOf(i)).start();
}
}
}
5.2、Set不安全
package com.chen.unsafe;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentSkipListSet;
/**
* 同理可证:ConcurrentModificationException
* 解决方案:
* 1、Set<Object> set = Collections.synchronizedSet(new HashSet<>());
* 2、Set<Object> set =new ConcurrentSkipListSet<>(new HashSet<>());
*/
public class SetTest {
public static void main(String[] args) {
// Set<Object> set = new HashSet<>();
// Set<Object> set = Collections.synchronizedSet(new HashSet<>());
Set<Object> set =new ConcurrentSkipListSet<>(new HashSet<>());
for (int i = 1; i < 30; i++) {
new Thread(()->{
set.add(UUID.randomUUID().toString().substring(0,5));
System.out.println(set);
}).start();
}
}
}
hashSet 底层?
public HashSet() {
map = new HashMap<>();
}
// add set 本质就是map key是无法重复的
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
// 不变的值!
private static final Object PRESENT = new Object();
5.3、HashMap
/**
* 解决方案
* 1、Map<String, String> map = Collections.synchronizedMap(new HashMap<>());
* 2、Map<String, String> map = new ConcurrentHashMap<>(new HashMap<>());
*/
public class MapTest {
public static void main(String[] args) {
// map 是这样用的吗? 不是,工作中不用HashMap
// 默认等价于什么?new HashMap<>(16,0.75)
Map<String, String> map = new ConcurrentHashMap<>(new HashMap<>());
for (int i = 1; i < 30; i++) {
new Thread(()->{
map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0,5));
System.out.println(map);
},String.valueOf(i)).start();
}
}
}