鍍金池/ 問答/Java  PHP/ hashset set方法取值問題,運行結(jié)果中,結(jié)果集只有一個元素,size()

hashset set方法取值問題,運行結(jié)果中,結(jié)果集只有一個元素,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、一種可能的結(jié)果

[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、問題
為什么集合中元素和打印的個數(shù)不匹配### 題目描述

題目來源及自己的思路

相關(guān)代碼

// 請把代碼文本粘貼到下方(請勿用圖片代替代碼)

你期待的結(jié)果是什么?實際看到的錯誤信息又是什么?

回答
編輯回答
笑忘初

HashSet使用add方法就是調(diào)HashMap的put方法,list.size()就是HashMap的size()方法,返回HashMap的size屬性,
list的size大于1是因為HashMap并發(fā)導致線程安全問題。
換成Set<Singleton2> list =Collections.synchronizedSet(new HashSet<Singleton2>());即可

2017年1月29日 14:47
編輯回答
我以為

Java 關(guān)于 HashSet 的文檔中明確表明該類不是線程安全的,所以絕對不要用多個線程操作同一個 HashSet 對象。

2017年4月22日 11:07