日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

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

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

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)部類
屬于懶漢式單例,因?yàn)镴ava機(jī)制規(guī)定,內(nèi)部類SingletonHolder只有在getInstance()方法第一次調(diào)用的時(shí)候才會(huì)被加載(實(shí)現(xiàn)了lazy),而且其加載過程是線程安全的。內(nèi)部類加載的時(shí)候?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 }

?

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

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

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實(shí)例變量用volatile修飾就可以了,volatile修飾的話就可以確保instance = new Singleton();對(duì)應(yīng)的指令不會(huì)重排序,如下的單例代碼也是線程安全的:

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é)

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

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