import java.util.Random;
public class Test{
public static void main(String[] args) {
Singleton instance = Singleton.getInstance();
System.out.println(instance);
Singleton instance2 = Singleton.getInstance();
System.out.println(instance2);
}
}
class Singleton{
private Singleton(){
}
// //饿汉式
// private static volatile Singleton Instance = new Singleton();
// public static Singleton getInstance(){
// return Instance;
// }
// //懒汉式
// private static volatile Singleton Instance;
// public synchronized static Singleton getInstance(){
// if(Instance==null){
// Instance = new Singleton();
// }
// return Instance;
// }
// //双重检验锁(DCL)
// private static volatile Singleton Instance;
// /**
// * 一定要加volatile,这是因为Instance = new Singleton();这一步并不是原子性的;会有这样三个步骤:
// * 第一步:为需要创建的对象分配地址空间
// * 第二步:在地址空间中初始化对象
// * 第三步:将Instance引用指向地址空间
// * 由于指令具有重排序优化的特性,所以可能会发生:1->3->2;(因为第二步和第三步无联系);
// * 所以当执行完第三步时,可能对象还未初始化;
// * 此时第二个线程访问的时候,判断Instance并不为空,则直接将未初始化的Instance返回了;
// * 之后利用该未初始化的Instance可能会出现空指针异常的错误
// */
// public static Singleton getInstance(){
// if(Instance==null){
// synchronized (Singleton.class){
// if(Instance==null){
// Instance = new Singleton();
// }
// }
// }
// return Instance;
// }
//静态内部类实现单例,当第一次调用getInstance方法的时候虚拟机会加载SingletonHandler类,并创建Instance实例
public static Singleton getInstance(){
return SingletonHandler.Instance;
}
private static class SingletonHandler{
private static Singleton Instance = new Singleton();
}
}