1, the following code
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;jPP) {
CountDownLatch c = new CountDownLatch(1000);
Set<Singleton2> list = new HashSet<Singleton2>();
for(int i= 0 ;i<1000;iPP) {
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, a possible result
[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, question
Why the number of elements in the collection does not match the number printed-sharp-sharp-sharp topic description
sources of topics and their own ideas
related codes
/ / Please paste the code text below (do not replace the code with pictures)