public class Singleton {
private static AtomicReference<Singleton> singleton = new AtomicReference<>();
private Singleton() {
}
public static Singleton getInstance() {
for (; ;) {
Singleton result = singleton.get();
if (result != null ) {
return result;
}
result = new Singleton();
if (singleton.compareAndSet(null, result)) {
return result;
}
}
}
public static void main(String[] args) {
System.out.println(Singleton.getInstance());
System.out.println(Singleton.getInstance());
System.out.println(Singleton.getInstance());
System.out.println(Singleton.getInstance());
System.out.println(Singleton.getInstance());
System.out.println(Singleton.getInstance());
}
private static AtomicReference<Singleton> singleton = new AtomicReference<>();
private Singleton() {
}
public static Singleton getInstance() {
for (; ;) {
Singleton result = singleton.get();
if (result != null ) {
return result;
}
result = new Singleton();
if (singleton.compareAndSet(null, result)) {
return result;
}
}
}
public static void main(String[] args) {
System.out.println(Singleton.getInstance());
System.out.println(Singleton.getInstance());
System.out.println(Singleton.getInstance());
System.out.println(Singleton.getInstance());
System.out.println(Singleton.getInstance());
System.out.println(Singleton.getInstance());
}
}
运行结果:
com.ll.wrapper.Singleton@6d06d69c
com.ll.wrapper.Singleton@6d06d69c
com.ll.wrapper.Singleton@6d06d69c
com.ll.wrapper.Singleton@6d06d69c
com.ll.wrapper.Singleton@6d06d69c
com.ll.wrapper.Singleton@6d06d69c