鐵子們有段時間沒有更新了,最近忙著準備面試,準備過程中發(fā)現(xiàn)自己還需要積累的實在是太多太多,每每學到新東西的感覺真是美妙而又動力十足啊,繼續(xù)伸直腰桿、努力前進
單例模式-DCL
雙重檢查判斷,使用volatile關鍵字禁止指令重排,在多線程情況下創(chuàng)建安全的單例對象,直接上代碼
public class Instance {
/**
* volatile 禁止指令重排,按照代碼執(zhí)行順序先賦值后創(chuàng)建對象
*/
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;
}
}