推荐使用的三种无线程安全问题的单例模式

1、饿汉式

public class Singleton        
{        
    private static Singleton instance = new Singleton();        
    private Singleton(){           
    }        
    public static Singleton getInstance(){        
             return instance;         
    }        
}

2、懒汉式的双重检查锁定

public class Singleton2 {
    
    private Singleton2() {}
    
    private static volatile Singleton2 instance;
    
    /**
     * 双重检查加锁
     * 
     * @return
     */
    public static Singleton2 getInstance () {
        // 自旋   while(true)
        if(instance == null) {//synchronized作为重量级锁,第一次实例化对象时候使用,读取的时候没必要进行代码锁定
            synchronized (Singleton2.class) {
                if(instance == null) {
                    instance = new Singleton2();  // 指令重排序
                    
                    // 申请一块内存空间   // 1
                    // 在这块空间里实例化对象  // 2
                    // instance的引用指向这块空间地址   // 3
                    //因此使用volatile防止指令重排序
                }
            }
        }
        return instance;
    }
}

3、内部类

public class Singleton{        
    private Singleton(){              
    }        
    private static class SingletonContainer{        
        private static Singleton instance = new Singleton();        
    }        
    public static Singleton getInstance(){        
        return SingletonContainer.instance;        
    }        
}
原文地址:https://www.cnblogs.com/mars-zyt/p/10059029.html