手写doublecheck

/**
 * description:doublecheck是为了保证在多线程下的单例模式
 *
 * @author 70KG
 * @date 2018/11/5
 */
public class Singleton {

    // 加volatile关键字是防止指令重排,保证了变量在内存中的可见性,但不能保证原子性。
    private volatile static Singleton instance = null;

    private Singleton() {
    }

    public static Singleton getInstance() {
        if (instance == null) {// 此处是为了减少加锁
            synchronized (Singleton.class) {
                if (instance == null) {// 此处为了并发进来后不要重复new对象
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }

}

猜你喜欢

转载自www.cnblogs.com/zhangjianbing/p/9908594.html