多线程下的两种单例写法

1:以volatile关键字和synchronized关键字实现

public class Sinstance {
    private static volatile Sinstance sinit = null;
    public static Sinstance getInstance() {
        Sinstance s = sinit;
        if (sinit == null) {
            s = sinit;
            if (s == null) { // 双重检测
                s = new Sinstance(); 
                sinit = s;  // volatile 关键字保证了代码在被译的顺序不会被改变,从而sinit 会在s 执行完构造方法后被赋值
            }
        }
        return s;
    }    
}

2:内部类方法。内部类方法可以实现延迟加载,并且线程安全是由jvm内部实现的

public class HelperHolder {
    public static class Helper {
        private static final Helper helper = new Helper();
    }
    public static Helper getHelper() {
        return Helper.helper;
    }
}
原文地址:https://www.cnblogs.com/taixuyingcai/p/5305427.html