像一些如list、set、map集合类 在多线程的场景下是不安全的,对此有三种常见的解决方案:
1、
List<String> list= new Vector<>();
Set<String> set= new Vector<>();
Set<String> set= new Vector<>();
2、
List<String> list= Collections.synchronizedList(new ArrayList<>());
Set<String> set=Collections.synchronizedSet(new HashSet<>());
Map<String,String> map=Collections.synchronizedMap(new HashMap<>());
3、
List<String> list=new CopyOnWriteArrayList<>();
Set<String> set=new CopyOnWriteArraySet<>();
Map<String,String> map=new ConcurrentHashMap<>();
一般建议使用第三种,因为第一种和第二种都是用了syncronized锁,所以执行效率不如第三种。