單例模式的餓漢式和懶漢式

使用單例模式,多個線程操作同一個對象,保證對象的唯一性

餓漢式

public class HungerySingleton {
    private static HungerySingleton instance = new HungerySingleton() ;
    private HungerySingleton(){}
    public static HungerySingleton getInstance(){
        return instance ;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 20; i++) {
            new Thread(() -> {
                HungerySingleton instance = getInstance();
                System.out.println(instance);
            }).start();
        }
    }
}

餓漢式:線程安全,在加載的時候實例化,只有一次所以是安全的 。性能比較好。
餓漢式很簡單就是類加載的時候就進行實例化。

懶漢式

單例中的懶漢式有幾種寫法,這裏就寫一個雙重檢驗鎖

public class DCL {
    private volatile static DCL instance = null ;
    private DCL(){}
    public static DCL getInstance(){
        if(null == instance) {
            synchronized (DCL.class) {
                if(instance == null) {
                    instance = new DCL() ;
                }
            }
        }
        return instance ;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 20; i++) {
            new Thread(() -> {
                DCL instance = getInstance();
                System.out.println(instance);
            }).start();
        }
    }
}

這段代碼跟小夥伴討論了一下,下面說一下我的想法
在這裏插入圖片描述
這裏只有兩段簡單的代碼,如果如果有什麼問題,請大家指教
單例模式還有Holder和枚舉的寫法,不太瞭解 ,所以就不寫了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章