单利模式(饿汉模式,懒汉模式)线程安全与解决问题

 

单例模式

1.饿汉模式:在类被加载的时候创建实例(线程安全的)

2.懒汉模式:在方法被运行的时候创建实例(线程不安全的) 解决方法:通过双检验

饿汉模式:

public class Singleton {
    //饿汉模式
    //将构造函数私有化
    private Singleton(){

    }
    //将对象实例化
    private static Singleton instance = new Singleton();

    //得到实例的方法

    public static Singleton getInstance() {
        return instance;
    }
}

 

懒汉模式:

//懒汉模式
    //将构造函数私有化
    private Singleton(){

    }
    //将对象实例化
    private static Singleton instance ;

    //得到实例的方法

    public static Singleton getInstance() {
       if(instance == null){
           instance = new Singleton();
       }
        return instance;
    }

 

解决方法1(慢)

//得到实例的方法

    synchronized public static Singleton getInstance() {
       if(instance == null){
           instance = new Singleton();
       }
        return instance;
    }

 

解决方法2(慢)

 //得到实例的方法

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

 

解决方法3(推荐)

原因:如果实例已经存在,就不存在线程安全的问题,可以直接获取实例,减少了加锁而造成的速度问题。

public class Singleton {
    //懒汉模式
    //将构造函数私有化
    private Singleton(){

    }
    //将对象实例化
    private static volatile  Singleton instance ;

    //得到实例的方法

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

volatile 关键字

 

转载于:https://www.cnblogs.com/da-peng/p/8278714.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值