日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

线程安全的单例模式的几种实现方法分享

發(fā)布時間:2025/7/14 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 线程安全的单例模式的几种实现方法分享 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

1、餓漢式單例

?

1 public class Singleton { 2 private final static Singleton INSTANCE = new Singleton(); 3 4 5 private Singleton() { } 6 7 public static Singleton getInstance() { 8 return INSTANCE; 9 } 10 }

?

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

1 public class Singleton { 2 3 4 private Singleton() { } 5 6 7 private static class SingletonHolder { 8 private final static Singleton INSTANCE = new Singleton(); 9 } 10 11 public static Singleton getInstance() { 12 return SingletonHolder.INSTANCE; 13 } 14 }

3、普通加鎖解決

1 public class Singleton { 2 3 4 private Singleton() { } 5 6 7 private static class SingletonHolder { 8 private final static Singleton INSTANCE = new Singleton(); 9 } 10 11 public static Singleton getInstance() { 12 return SingletonHolder.INSTANCE; 13 } 14 }

?

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

4、雙重檢測,但要注意寫法

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;} }

?

由于指令重排序問題,所以不可以直接寫成下面這樣:

1 public class Singleton { 2 private static Singleton instance = null; 3 4 private Singleton() { } 5 6 public static Singleton getInstance() { 7 if(instance == null) { 8 synchronzied(Singleton.class) { 9 if(instance == null) { 10 instance = new Singleton(); 11 } 12 } 13 } 14 15 return instance; 16 } 17 }

?

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

1 public class Singleton { 2 private static volatile Singleton instance = null; 3 4 private Singleton() { } 5 6 public static Singleton getInstance() { 7 if(instance == null) { 8 synchronzied(Singleton.class) { 9 if(instance == null) { 10 instance = new Singleton(); 11 } 12 } 13 } 14 15 return instance; 16 } 17 }

?

?

您可能感興趣的文章:

轉(zhuǎn)載于:https://www.cnblogs.com/blog-cq/p/5648856.html

總結(jié)

以上是生活随笔為你收集整理的线程安全的单例模式的几种实现方法分享的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。