java双重判断单例懒汉式_Java设计模式-单例模式-懒汉式-双重检查

优缺点说明

1)双重检查概念是多线程开发中常使用到的,如代码中所示,我们进行了两次if (singleton == null) 检查,这样就可以保证线程安全了

2)这样,实例化代码只用执行一次,后面再次访问时,判断if (singleton == null) ,直接return实际化对象,也避免的反复进行方法同步

3)线程安全、延迟加载、效率较高

4)结论:在实际开发中,推荐使用这种单例设计模式

public class SingletonTest06 {

public static void main(String[] args) {

Singleton06 instance = Singleton06.getInstance();

Singleton06 instance01 = Singleton06.getInstance();

System.out.println(instance == instance01);

System.out.println("instance,hashCode= " + instance.hashCode());

System.out.println("instance01,hashCode = " + instance01.hashCode());

}

}

class Singleton06 {

private static volatile Singleton06 singleton;

private Singleton06() {

}

public static Singleton06 getInstance() {

if (singleton == null) {

synchronized (Singleton06.class) {

if (singleton == null) {

singleton = new Singleton06();

}

}

}

return singleton;

}

}

// 运行结果

true

instance,hashCode= 1846274136

instance01,hashCode = 1846274136

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值