账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    hashset set方法取值问题,运行结果中,结果集只有一个元素,size() 获取的值 > 1
    18
    0

    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、问题
    为什么集合中元素和打印的个数不匹配### 题目描述

    题目来源及自己的思路

    相关代码

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

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

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 采风西南 普通会员 1楼
      502 Bad Gateway

      502 Bad Gateway


      nginx
    更多回答
    网站公告
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部