铁子们有段时间没有更新了,最近忙着筹备面试,筹备过程中发现自己还须要积攒的切实是太多太多,每每学到新货色的感觉真是美好而又能源十足啊,持续蜷缩腰杆、致力后退
单例模式 -DCL
双重查看判断,应用 volatile 关键字禁止指令重排,在多线程状况下创立平安的单例对象,间接上代码
public class Instance {
/**
* volatile 禁止指令重排,依照代码执行程序先赋值后创建对象
*/
private volatile static Instance instance;
private String instName;
private Instance() {instName = "DCL";}
public static Instance getInstance() {if (instance == null) {synchronized (Instance.class) {if (instance == null) {instance = new Instance();
}
}
}
return instance;
}
}
单例模式 - 外部类
应用外部类结构单例对象,JVM 保障单例
public class Instance {
private static class InstanceObj {private static final Instance INSTANCE = new Instance();
}
public static Instance getInstance() {return InstanceObj.INSTANCE;}
}