双检锁: 双重检验锁
public class Single {
private volatile Single instance;
public Single getInstance() {
if (instance == null) {
synchronized (Single.class) {
if (instance == null)
instance = new Single();
}
}
return instance;
}
}
volatile
关键字必须加,为了防止指令重排。
这段代码实际分为三步: