前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java中四种线程安全的单例模式实现方式

Java中四种线程安全的单例模式实现方式

作者头像
HaC
发布2020-12-30 17:59:01
2.8K0
发布2020-12-30 17:59:01
举报
文章被收录于专栏:HaC的技术专栏

第一种:饿汉模式(线程安全)

代码语言:javascript
复制
public class Single2 {

    private static Single2 instance = new Single2();
    
    private Single2(){
        System.out.println("Single2: " + System.nanoTime());
    }
    
    public static Single2 getInstance(){
        return instance;
    }
}

第二种:懒汉模式 (如果方法没有synchronized,则线程不安全)

代码语言:javascript
复制
public class Single3 {

    private static Single3 instance = null;
    
    private Single3(){
        System.out.println("Single3: " + System.nanoTime());
    }
    
    public static synchronized Single3 getInstance(){
        if(instance == null){
            instance = new Single3();
        }
        return instance;
    }
}

第三种:懒汉模式改良版(线程安全,使用了double-check,即check-加锁-check,目的是为了减少同步的开销)

代码语言:javascript
复制
public class Single4 {

    private volatile static Single4 instance = null;
    
    private Single4(){
        System.out.println("Single4: " + System.nanoTime());
    }
    
    public static Single4 getInstance(){
        if(instance == null){
            synchronized (Single4.class) {
                if(instance == null){
                    instance = new Single4();
                }
            }
        }
        return instance;
    }
}

第四种:利用私有的内部工厂类(线程安全,内部类也可以换成内部接口,不过工厂类变量的作用于要改为public了。)

代码语言:javascript
复制
public class Singleton {
    
    private Singleton(){
        System.out.println("Singleton: " + System.nanoTime());
    }
    
    public static Singleton getInstance(){
        return SingletonFactory.singletonInstance;
    }
    
    private static class SingletonFactory{
        private static Singleton singletonInstance = new Singleton();
    }
}

转自:https://www.nowcoder.com/profile/6801164/myFollowings/detail/13699402

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/09/29 ,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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