java和C++之單例類雙重檢查加鎖

1、Java
public class Singleton {
    private volatile static Singleton instance;
    public static Singleton getInstance () {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

2、C++
class Singleton {
    private:
        volatile Singleton* pInst = 0;
    public:
        static Singleton* GetInstance() {
            if (pInst == 0) {
                lock();
                if (pInst == 0) {
                    pInst = new Singleton();
                }
                unlock();
            }
            return pInst;
        }
}

3、總結(jié)
同步機(jī)制等價(jià)于鎖機(jī)制


作者:chen.yu
深信服三年半工作經(jīng)驗(yàn),目前就職游戲廠商,希望能和大家交流和學(xué)習(xí),
微信公眾號(hào):編程入門到禿頭 或掃描下面二維碼
零基礎(chǔ)入門進(jìn)階人工智能(鏈接)