国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 蒙阴县| 隆昌县| 论坛| 枞阳县| 家居| 西丰县| 江安县| 贵州省| 张家界市| 宝丰县| 柳河县| 称多县| 壤塘县| 齐齐哈尔市| 兴隆县| 榆林市| 乾安县| 闽侯县| 淮滨县| 申扎县| 冀州市| 长泰县| 兴文县| 澄江县| 台东市| 焉耆| 石泉县| 镇雄县| 邳州市| 连山| 息烽县| 大宁县| 吉木萨尔县| 海城市| 西宁市| 古交市| 新绛县| 苗栗县| 滦平县| 荣昌县| 沅江市|