單利模式(餓漢模式,懶漢模式)線程安全與解決問題


 

單例模式

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 關鍵字

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM