DCL单例模式
【小城贝尔】
私有默认构造器,静态方法调实例。
加入线程同步锁,双重检查上边过。
指令重排风险在,懒汉前边vola在。
package concurrently.HappenBefore;
public class DoubleCheakingLocking {
//静态属性
private volatile static DoubleCheakingLocking instance;
//私有化构造器
private DoubleCheakingLocking() {
}
public static DoubleCheakingLocking getDoubleCheakingLocking(){
//加入双重检查
if(instance != null){
return instance;
}
synchronized (DoubleCheakingLocking.class){
if (instance == null){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
instance = new DoubleCheakingLocking();
}
}
return instance;
}
}
class TestDcl{
public static void main(String[] args) {
System.out.println(DoubleCheakingLocking.getDoubleCheakingLocking());
System.out.println(DoubleCheakingLocking.getDoubleCheakingLocking());
/*
concurrently.HappenBefore.DoubleCheakingLocking@6474c2
concurrently.HappenBefore.DoubleCheakingLocking@6474c2
*/
}
}