arraylist hashmap hashset 多线程下java.util.ConcurrentModificationException 异常问题

List<String> list = new ArrayList<>();
Set<String> set = new HashSet<>();
Map<String,String> map = new HashMap<>();

1. 使用  线程安全的 Vector

List<String> list = new Vector<>();

2.使用 collections工具类

List<String> list = Collections.synchronizedList(new ArrayList<>());
Set<String> set = Collections.synchronizedSet(new HashSet<>());
Map<String,String> map = Collections.synchronizedMap(new HashMap<>());


3.使用juc工具包 的类
List<String> list = new CopyOnWriteArrayList<>();
Set<String> set = new CopyOnWriteArraySet<>();
Map<String,String> map = new ConcurrentHashMap<>();
map的这个方法和上面的名字不太相似,但都是利用数据的复制和读写分离来实现的,
在有用户写入数据时,先copy一份,在copy的这份数据上修改,
该数据只能一个线程进来写数据,该线程进来时需要拿到锁,修改完数据后在释放锁,另一个线程拿到锁之后才能进来修改数据。
另一份数据供其他线程读取数据不加锁


posted @ 2020-04-01 15:56  荣超  阅读(390)  评论(0)    收藏  举报