【Java學習】單例模式

來源:互聯網
上載者:User

標籤:sync   方式   zed   操作   get   java學習   線程   問題   解決   

單例模式有兩種:餓漢模式和懶漢模式,懶漢模式的特點是消極式載入執行個體

//餓漢模式
class Singleton1{
  private static final Singleton1 instance = new Singleton1();
  private Singleton1(){}
  public static Singleton1 getSingleton()
  {
    return instance;
  }
}

//懶漢模式 
class Singleton2{
  private static Singleton2 instance;
  private Singleton2(){}
  public static Singleton2 getSingleton()
  {
    if(instance == null)
      instance = new Singleton2();
    return instance;
  }
}

懶漢模式在多線程的情況下,會存在安全問題,對象會被執行個體化多次,可以用同步方法或者同步方法快的方式解決

//解決懶漢模式多線程的安全問題
class Singleton3{
  private static Singleton3 instance;
  private Singleton3(){}
  public static synchronized Singleton3 getSingleton()
  {
    if(instance == null)
      instance = new Singleton3();
    return instance;
  }
}

但是這種方式由於增加了判斷鎖的操作,會使得執行效率變慢

//解決懶漢模式多線程的安全問題的最佳化方案
class Singleton4{
  private static Singleton4 instance;
  private Singleton4(){}
  public static Singleton4 getSingleton()
  {
    if(instance == null)
    {
      synchronized(Singleton4.class)
      {
        if(instance == null)
          instance = new Singleton4();
      }
    }
    return instance;
  }
}

【Java學習】單例模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.