關於雙重檢驗鎖方法和內部類方法實現單例模式的實驗

網上不少人說,使用雙重檢驗鎖方法實現單例模式可能會new多個實例,而內部類方法和枚舉類方法完美解決了這個問題

由於Android不多使用枚舉,本次只研究雙重檢驗鎖方法和內部類方法

雙重檢驗鎖方法:

代碼以下:android

public class SingletonB {
    private static volatile SingletonB mInstance;

    private SingletonB() {
        System.out.println("雙重檢驗鎖方法單例模式");
    }

    public static SingletonB getInstance() {
        if (mInstance == null) {
            synchronized (SingletonB.class) {
                if (mInstance == null) {
                    mInstance = new SingletonB();
                }
            }
        }
        return mInstance;
    }
}

內部類方法:

代碼以下:多線程

public class SingletonA {
    private SingletonA() {
        System.out.println("內部類方法單例模式");
    }

    private static class Singleton {
        private static final SingletonA INSTANCE = new SingletonA();
    }

    public static SingletonA getInstance() {
        return Singleton.INSTANCE;
    }
}

在多線程環境下分別使用這兩種單例模式

測試代碼:函數

public class Test {

    public static void main(String[] args) {
        Thread[] threads = new Thread[10000];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread() {
                public void run() {
                    SingletonA.getInstance();
                    SingletonB.getInstance();
                };
            };
        }
        for (int i = 0; i < threads.length; i++) {
            threads[i].start();
        }
    }

}

運行結果

運行了N次,兩個單例模式都是隻運行了一次構造函數。測試

其實個人指望是能出現雙重鎖方法的bad case,可是並無出現。本次實驗失敗,下次再接再礪。

相關文章
相關標籤/搜索