单例模式分为两种,饿汉式与懒汉式

1.饿汉式,随着类加载时被完成初始化,缺点是有可能浪费资源

class SingletonLazy {
    //懒汉式直接创建对象
    private static SingletonLazy singletonLazy = new SingletonLazy();

    private static SingletonLazy getInstance() {
        return singletonLazy;
    }
}

2.懒汉式,懒汉式双重校验锁(线程安全)

 

class SingletonHungry {
    //加volatile关键字是防止指令重排
    private static volatile  SingletonHungry singletonHungry;
    private static SingletonHungry getInstance() {
        //这一步是减少不必要的加锁损耗资源
        if (singletonHungry == null) {
            synchronized (SingletonHungry.class) {
                //这一步是第一个线程进来加锁进行对象的初始化
                if (singletonHungry == null) {
                    singletonHungry = new SingletonHungry();
                }
            }
        }
        return singletonHungry;
    }
}

 

Rick  46浏览  0评论  2020-09-26

上一篇