国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Java > 正文

線程安全的單例模式的幾種實(shí)現(xiàn)方法分享

2019-11-26 15:41:48
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

1、餓漢式單例

復(fù)制代碼 代碼如下:

public class Singleton {
   private final static Singleton INSTANCE = new Singleton();

   private Singleton() { }

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

2、借助內(nèi)部類
屬于懶漢式單例,因?yàn)镴ava機(jī)制規(guī)定,內(nèi)部類SingletonHolder只有在getInstance()方法第一次調(diào)用的時(shí)候才會(huì)被加載(實(shí)現(xiàn)了lazy),而且其加載過(guò)程是線程安全的。內(nèi)部類加載的時(shí)候?qū)嵗淮蝘nstance。

復(fù)制代碼 代碼如下:

public class Singleton {

   private Singleton() { }

   private static class SingletonHolder {
      private final static Singleton INSTANCE = new Singleton();
   }

   public static Singleton getInstance() {
      return SingletonHolder.INSTANCE;
   }
}

3、普通加鎖解決

復(fù)制代碼 代碼如下:

public class Singleton {
   private static Singleton instance = null;

   private Singleton() { }

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

      return instance;
   }
}

雖然解決了線程安全問(wèn)題,但是每個(gè)線程調(diào)用getInstance都要加鎖,我們想要只在第一次調(diào)用getInstance時(shí)加鎖,請(qǐng)看下面的雙重檢測(cè)方案

4、雙重檢測(cè),但要注意寫法

復(fù)制代碼 代碼如下:

public class Singleton {
   private static Singleton instance = null;

   private Singleton() { }

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

      return instance;
   }
}

由于指令重排序問(wèn)題,所以不可以直接寫成下面這樣:
public class Singleton {
   private static Singleton instance = null;

   private Singleton() { }

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

      return instance;
   }
}

但是如果instance實(shí)例變量用volatile修飾就可以了,volatile修飾的話就可以確保instance = new Singleton();對(duì)應(yīng)的指令不會(huì)重排序,如下的單例代碼也是線程安全的:
public class Singleton {
   private static volatile Singleton instance = null;

   private Singleton() { }

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

      return instance;
   }
}

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 盘锦市| 德昌县| 黄平县| 石门县| 洪江市| 仙游县| 临武县| 湛江市| 威海市| 乌恰县| 常州市| 台东市| 子洲县| 牙克石市| 库尔勒市| 井冈山市| 焦作市| 阿克陶县| 柯坪县| 西盟| 玉田县| 汉中市| 财经| 会理县| 吉木萨尔县| 新乡县| 鄂伦春自治旗| 满城县| 肥城市| 叙永县| 城市| 绥化市| 名山县| 夹江县| 石屏县| 凤凰县| 阿勒泰市| 南阳市| 长顺县| 榆中县| 乌兰县|