前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java设计模式-单例模式-懒汉式-双重检查

Java设计模式-单例模式-懒汉式-双重检查

作者头像
桑鱼
发布2020-03-17 15:17:25
7100
发布2020-03-17 15:17:25
举报
文章被收录于专栏:学习笔记持续记录中...

优缺点说明

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

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

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

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

代码语言:javascript
复制
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
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 优缺点说明
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档