hashset set方法取值问题,运行结果中,结果集只有一个元素,size() 获取的值 > 1

新手上路,请多包涵

1、如下代码

package gof.singleton;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CountDownLatch;

//多线程安全
public class Singleton2 {
    
    private static Singleton2 singleton = new Singleton2();
    
    private Singleton2() {}
    
    public static Singleton2 getSingleton() {
        return singleton;
    }
    
    public static void main(String[] args) throws InterruptedException {
        
        for(int j = 0;j<10;j++) {
            CountDownLatch c = new CountDownLatch(1000);
            Set<Singleton2> list = new HashSet<Singleton2>();
            for(int i= 0 ;i<1000;i++) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(2);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        list.add(Singleton2.getSingleton());
                        c.countDown();
                    }
                }).start();
            }
            c.await();
            System.out.println(list + "-" + list.size());
            //list.stream().forEach(System.out::println);
        }
        
        
        
    }
}

2、一种可能的结果

[gof.singleton.Singleton2@a627065]-3
[gof.singleton.Singleton2@a627065]-5
[gof.singleton.Singleton2@a627065]-2
[gof.singleton.Singleton2@a627065]-5
[gof.singleton.Singleton2@a627065]-2
[gof.singleton.Singleton2@a627065]-1
[gof.singleton.Singleton2@a627065]-4
[gof.singleton.Singleton2@a627065]-3
[gof.singleton.Singleton2@a627065]-1
[gof.singleton.Singleton2@a627065]-3

3、问题
为什么集合中元素和打印的个数不匹配### 题目描述

题目来源及自己的思路

相关代码

// 请把代码文本粘贴到下方(请勿用图片代替代码)

你期待的结果是什么?实际看到的错误信息又是什么?

阅读 5.7k
2 个回答

HashSet使用add方法就是调HashMap的put方法,list.size()就是HashMap的size()方法,返回HashMap的size属性,
list的size大于1是因为HashMap并发导致线程安全问题。
换成Set<Singleton2> list =Collections.synchronizedSet(new HashSet<Singleton2>());即可

Java 关于 HashSet 的文档中明确表明该类不是线程安全的,所以绝对不要用多个线程操作同一个 HashSet 对象。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题