JUC Concurrent Programming Set Collection (5)

 

 

package com.xizi.unsafe;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;

//java.util.ConcurrentModificationException
public class SetTest {
    public static void main(String[] args) {
//        HashSet<String> set = new HashSet<>();
//        解决方案
//        1.Set<String> set= Collections.synchronizedSet(new HashSet<>());
//        2.Set<String> set = new CopyOnWriteArraySet<>();

        Set<String> set = new CopyOnWriteArraySet<>();
        for (int i = 0; i < 30; i++) {
            new Thread(()->{
                set.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println( set);
            },String.valueOf(i)).start();
        }

    }
}

 

What is the bottom layer of hashSet? 

public HashSet() { 
    map = new HashMap<>(); 
}

The essence of the add method set is that the map key cannot be repeated
public boolean add(E e) {     return map.put(e, PRESENT)==null; }

 

Guess you like

Origin blog.csdn.net/weixin_45480785/article/details/105358372