单例模式获取单例对象

不会产生性能问题,有启发。

public static Manager getInstance() {
        if (inst != null) {
            return inst;
        }
        synchronized (Manager.class) {
            if (inst == null) {
                inst = new Manager();
            }
        }
        return inst;
    }

另一种写法

 public static Manager getInstance() {
        if (instance == null) {
            synchronized (obj) {
                if (instance == null) {
                    instance = new Manager();
                }
            }
        }
        return instance;
    }

有个专业词汇:
双检锁/双重校验锁(DCL,即 double-checked locking)
下面介绍一种双检锁的实现方式,这种方式看起来稍稍比较复杂了点,不过可以实现线程安全,同时双检锁的方式可以保证性能比较高

p

ublic class Singleton {
 
    //定义private构造函数,使类不可以被实例
    private Singleton (){}

    private volatile static Singleton instance;

    /**
     * 双检锁/双重校验锁(DCL,即 double-checked locking)线程安全,懒加载
     * @return
     */
    public static Singleton getInstance(){
        if(instance == null){
            synchronized (Singleton.class){
                if(instance == null){
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值