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;
}
}
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;
}
}
private:
volatile Singleton* pInst = 0;
public:
static Singleton* GetInstance() {
if (pInst == 0) {
lock();
if (pInst == 0) {
pInst = new Singleton();
}
unlock();
}
return pInst;
}
}
3、總結
同步機制等價于鎖機制
作者:chen.yu
深信服三年半工作經(jīng)驗,目前就職游戲廠商,希望能和大家交流和學習,
微信公眾號:編程入門到禿頭 或掃描下面二維碼
零基礎入門進階人工智能(鏈接)