5.集合类不安全之Set
package com.mydemo; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.UUID; import java.util.concurrent.CopyOnWriteArraySet; public class SetNotSafeDemo { public static void main(String[] args) { //HashSetset = new HashSet<>(); //CopyOnWriteArraySetset = new CopyOnWriteArraySet<>(); Setset = Collections.synchronizedSet(new HashSet ()); for (int i = 0; i < 30; i++) { new Thread(()->{ set.add(UUID.randomUUID().toString().substring(0,8)); System.out.println(set); },String.valueOf(i)).start(); } } }
解决方法:
- Collections.synchronizedSet(new HashSet<>())
- CopyOnWriteArraySet<>()(推荐)
2.HashSet底层是HashMap
public boolean add(E e) { return map.put(e, PRESENT)==null; }