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

Java设计模式-单例模式-懒汉式-同步代码块

作者头像
桑鱼
发布2020-03-17 15:16:48
4890
发布2020-03-17 15:16:48
举报

优缺点说明

1)这种方式,本意是想对懒汉式-线程安全这种方式进行的改进,因为前面同步方法效率太低,改为同步产生实例化的代码块

2)但是这种同步并不能起到线程同步的作用。跟懒汉式-线程不安全遇到的情形是一样的,假如一个线程进入了if (singleton == null)判断语句块,还没有来得及往下执行,另一个线程也通过了这个判断语句,这时便会产生多个实例

3)结论:在实际开发中,不能使用这种方式

代码语言:javascript
复制
public class SingletonTest05 {
    public static void main(String[] args) {
        Singleton05 instance  = Singleton05.getInstance();
        Singleton05 instance01 = Singleton05.getInstance();

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

class Singleton05{
    private static Singleton05 singleton05;
    private Singleton05(){}

    public static Singleton05 getInstance(){
        if (singleton05 == null){
            synchronized (Singleton05.class){
                singleton05 = new Singleton05();
            }
        }
        return singleton05;
    }
}

// 运行结果
true
instance,hashCode= 1846274136
instance01,hashCode = 1846274136
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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