多线程下单例模式的正确写法

来源:互联网 发布:模拟人生2汉化补丁mac 编辑:程序博客网 时间:2024/05/16 09:29
package com.peanut.singleton;/** * 多线程下正确的单例模式写法 * Created by peanut on 2016/4/25. */public class SingletonDemo {    private SingletonDemo() {    }    //synchronized    private static SingletonDemo instance;    private synchronized static SingletonDemo getInstance() {        if (instance == null)            instance = new SingletonDemo();        return instance;    }    //2、volatile+双重检查锁定    private volatile static SingletonDemo instance1;    private static SingletonDemo getInstance1() {        if (instance1 == null) {            synchronized (SingletonDemo.class) {                if (instance1 == null) {                    instance1 = new SingletonDemo();                }            }        }        return instance1;    }    //3、静态内部类实现    private static class SingletonHolder {        private static SingletonDemo instance2 = new SingletonDemo();    }    private static SingletonDemo getInstance2() {        return SingletonHolder.instance2;    }}
0 0