没啥可说的,2中解决方法。

    说一些题外话,hashSet的底层是Hashmap,可以看源码。这就是为啥,set是不可重复的,无序的了。

    1. import java.util.Collections;
    2. import java.util.HashSet;
    3. import java.util.Set;
    4. import java.util.UUID;
    5. import java.util.concurrent.CopyOnWriteArraySet;
    6. /**
    7. * 同理可证 : ConcurrentModificationException
    8. * //1、Set<String> set = Collections.synchronizedSet(new HashSet<>());
    9. * //2、
    10. */
    11. public class SetTest {
    12. public static void main(String[] args) {
    13. Set<String> set = new HashSet<>();
    14. // hashmap
    15. // Set<String> set = Collections.synchronizedSet(new HashSet<>());
    16. // Set<String> set = new CopyOnWriteArraySet<>();
    17. for (int i = 1; i <=30 ; i++) {
    18. new Thread(()->{
    19. set.add(UUID.randomUUID().toString().substring(0,5));
    20. System.out.println(set);
    21. },String.valueOf(i)).start();
    22. }
    23. }
    24. }