1、餓漢模式
public class HungrySingleton {
private static final HungrySingleton instance = new HungrySingleton();
private HungrySingleton(){}
public static HungrySingleton getInstance(){
return instance;
}
}
餓漢模式在類加載的時候就完成了實體化,所以沒有執行緒同步問題
2、懶漢模式
public class LazySingleton {
private static volatile LazySingleton instance = null;
//加private避免在外部被實體化
private LazySingleton(){}
public static LazySingleton getInstance(){
if (instance == null){
instance = new LazySingleton();
}
return instance;
}
}
適用于單執行緒,由于當執行緒1執行完 if (instance == null)后,還沒開始new物件,執行緒2可能已經通過了這個判斷并且已經實體化了物件,這時候就會產生多個物件
3、懶漢模式(加鎖)
public class LazySingleton {
//加上volatile關鍵字保證instance在所有執行緒中同步(操作可見性)
private static volatile LazySingleton instance = null;
//加private避免在外部被實體化
private LazySingleton(){}
//加synchronized同步
public static synchronized LazySingleton getInstance(){
if (instance == null){
instance = new LazySingleton();
}
return instance;
}
}
適用于多執行緒,在原基礎上加了雙重鎖(volatile和synchronized)可以保證在多執行緒環境下的安全問題
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/166429.html
標籤:其他
上一篇:k8s多節點儀表盤(web界面)部署與谷歌瀏覽器訪問k8s儀表盤問題解決!
下一篇:msf病毒制作
