java单例模式——双重检查
public class Singleton { private volatile static Singleton singleton; public static Singleton getSingleton() { if (singleton == null) { // 这里方法是static的,所以synchronized不能锁住this对象 // 只能锁住class对象 synchronized (Singleton.class) { if (singleton == null) { /** * 这就是为什么要家volatile关键字原因 * 1 防止对象没有初始化完成,其他线程使用未初始化的对象 * 2 相当于是禁止了指令重排 * */ singleton = new Singleton(); } } } return singleton; } }
除了双重检查的方式实现单例模式,还有静态内部类和枚举的方式可以实现单例模式