懒汉式单例+双重检查

demo:

public class Test {
    public static void main(String[] args) {
        SingletonInstance instance = SingletonInstance.getSingletonInstance();
        SingletonInstance instance2 = SingletonInstance.getSingletonInstance();
        System.out.println("是否是同一个实例:"+(instance == instance2));
    }
}
class SingletonInstance {

    private static volatile SingletonInstance singletonInstance = null;

    private SingletonInstance() { }

    public static SingletonInstance getSingletonInstance() {
        if (singletonInstance == null) {
            synchronized (SingletonInstance.class) {
                if (singletonInstance == null) {
                    singletonInstance = new SingletonInstance();
                }
            }
        }
        return singletonInstance;
    }
}

 

posted @ 2019-12-05 10:47  来一杯可乐  阅读(180)  评论(0编辑  收藏  举报