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

chen.yu發表於2020-10-09

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++

 

相關文章