🛸~~ 🚁🚁🚁🛩️🛩️�|

n1ce2cv

园龄:5年2个月粉丝:4关注:1

集合类不安全

集合类不安全

  • ConcurrentModificationException并发修改异常
  • 解决办法
    • 写入时复制
    • 使用工具类Collections
  • List不安全
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
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 写入时复制
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();
}
}
}
  • Set不安全
import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;
class SetTest {
public static void main(String[] args) {
/**
* 1.Set<String> set = Collections.synchronizedSet(new HashSet<>());
* 2.Set<String> set = new CopyOnWriteArraySet<>();
*/
Set<String> set = new CopyOnWriteArraySet<>();
for (int i = 0; i < 10; i++) {
new Thread(()->{
set.add(UUID.randomUUID().toString().substring(0, 5));
System.out.println(set);
}, String.valueOf(i)).start();
}
}
}
  • HashSet底层是HashMap
public HashSet() {
map = new HashMap<>();
}
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
  • HashMap不安全
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
class MapTest {
public static void main(String[] args) {
// 默认等价与new HashMap<>(16, 0.75); 初始化容量和加载因子
Map<String, String> map = new ConcurrentHashMap<>();
for (int i = 1; i <= 10; i++) {
new Thread(() -> {
map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0, 5));
System.out.println(map);
}, String.valueOf(i)).start();
}
}
}

本文作者:n1ce2cv

本文链接:https://www.cnblogs.com/sprinining/p/15485066.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   n1ce2cv  阅读(30)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起