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、问题
为什么集合中元素和打印的个数不匹配### 题目描述
题目来源及自己的思路
相关代码
// 请把代码文本粘贴到下方(请勿用图片代替代码)
HashSet使用add方法就是调HashMap的put方法,list.size()就是HashMap的size()方法,返回HashMap的size属性,
list的size大于1是因为HashMap并发导致线程安全问题。
换成Set<Singleton2> list =Collections.synchronizedSet(new HashSet<Singleton2>());即可