首页 > 编程语言 > 详细

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

时间:2018-01-13 13:46:03      阅读:262      评论:0      收藏:0      [点我收藏+]

 

单例模式

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!