单例模式写法的总结(保证线程安全)

首先,单例模式分为饿汉模式和懒汉模式

单例模式有什么用呢?

可以保证在程序运行过程中,一个类只有一个实例,而且该实例易于供外界访问,从而方便的控制了实例个数,并节约系统资源。

例如:DataSource(JDBC中)类对象只需要一个。

饿汉模式:知道你很饿,所以提前给你准备好了,于是在类加载的过程中创建实例,所以就写在static代码块中,和类一起加载。

static class Singleton {
        private static Singleton singleton = new Singleton();
        private Singleton() {}
        public static Singleton getSingleton() {
            return singleton;
        }
    }

懒汉模式:知道你很饿,但是当你第一次需要的时候我再给你,不需要的时候是没有我的实例对象给你调用的,这个实例对象通常由方法中创建,由方法来返回。

class Singleton {
    private static Singleton singleton = null;
    private Singleton() {}
    public static Singleton getSingleton() {
        if (singleton == null) {
            singleton = new Singleton();
       }
        return singleton;
   }
}
 

其中很关键的一步是private Singleton() {}这一句代码,让其他类没法调用它的构造方法。

因为饿汉模式提前创建好了,所以天生就是线程安全的。

而懒汉模式是需要才创建,那么多个线程中同时需要会怎么办?会不会出现线程安全问题?

会的,如果多个线程中同时调用getSingleton方法,那么就有可能同时创建出多个实例对象。

那么怎么解决这个线程安全问题呢?

使用synchronized关键字

public synchronized static Singleton getSingleton() {
        if (singleton == null) {
            singleton = new Singleton();
       }
        return singleton;
   }

能不能再改进一下?

为了解决线程安全性的可见性问题,使用volatile关键字

另外,再使用双重if语句判断,降低锁竞争的频率

private static volatile Singleton singleton = null;
 
 public static Singleton getSingleton() {
        if (singleton == null) {
            synchronized (Singleton.class) {
           if (singleton == null) {
               singleton = new Singleton();
               }
           }
       }
        return singleton;
   }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值