多線程下單例模式的正確寫法

package com.peanut.singleton;

/**
 * 多線程下正確的單例模式寫法
 * Created by peanut on 2016/4/25.
 */
public class SingletonDemo {

    private SingletonDemo() {
    }

    //synchronized
    private static SingletonDemo instance;

    private synchronized static SingletonDemo getInstance() {
        if (instance == null)
            instance = new SingletonDemo();
        return instance;
    }

    //2、volatile+雙重檢查鎖定
    private volatile static SingletonDemo instance1;

    private static SingletonDemo getInstance1() {
        if (instance1 == null) {
            synchronized (SingletonDemo.class) {
                if (instance1 == null) {
                    instance1 = new SingletonDemo();
                }
            }
        }
        return instance1;
    }

    //3、靜態內部類實現
    private static class SingletonHolder {
        private static SingletonDemo instance2 = new SingletonDemo();
    }

    private static SingletonDemo getInstance2() {
        return SingletonHolder.instance2;
    }

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