JUC-Set

作者: GIT提交不上 | 来源:发表于2020-02-25 18:18 被阅读0次

  HashSet构造函数:默认容量为16的HashMap。(底层是HashMap)

  /**
     * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
     * default initial capacity (16) and load factor (0.75).
     */
    public HashSet() {
        map = new HashMap<>();
    }

  HashSet的add方法:只关心键值,value为常量。

public boolean add(E e) {
    return map.put(e, PRESENT)==null;
}

  CopyOnWriteArraySet解决Set线程不安全性问题,代码如下:

/**
 * @author luffy
 **/
public class HashSetDemo {
    public static void main(String[] args){
        Set<String> set = new CopyOnWriteArraySet<>();
        //Set<String> set = 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();
        }
    }
}

  CopyOnWriteArraySet的构造方法,底层也是CopyOnWriteArrayList。

public CopyOnWriteArraySet() {
    al = new CopyOnWriteArrayList<E>();
}

相关文章

  • JUC-Set

      HashSet构造函数:默认容量为16的HashMap。(底层是HashMap)   HashSet的add方...

网友评论

      本文标题:JUC-Set

      本文链接:https://www.haomeiwen.com/subject/xtjxchtx.html