???????
???????????????????????????????????????????????????????????????????????У?????????楨????????????????????????????????????????????????Щ??????????????????????????????????????????????????????????????Printer Spooler??????????????????????????????С???????????????????????????????й?????Щ????????????????????????????????????á?????????????????????????????????????????
???????????
?????????????????
//?????о???????
private static Emperor singleton;
//  ??е??????
private Emperor() {
}
//  ????????????????
public static Emperor getSingleton() {
return singleton = new Emperor();
}
??????????????
????private static final Emperor singleton = new Emperor();
????//  ??е??????
????private Emperor() {
????}
????//  ????????????????
????public static Emperor getSingleton() {
????return singleton;
????}
??????????????????????????????????????????????????
??????????????
????????????????????
public class Emperor {
private static Emperor singleton;
//  ??е??????
private Emperor() {
}
//  ????????????????
public static Emperor getSingleton() {
if (singleton == null) {
singleton = new Emperor();
}
return singleton;
}
}
???????????????????????????????????
?????????????????????????
public class Emperor {
private static Emperor singleton;
//  ??е??????
private Emperor() {
}
//  ????????????????
public synchronized static Emperor getSingleton() {
if (singleton == null) {
singleton = new Emperor();
}
return singleton;
}
}
???????????μ????????????????????????ε???getSingleton???????????????
Double CheckLock??DCL????????
public class Emperor {
private static Emperor singleton;
//  ??е??????
private Emperor() {
}
//  ????????????????
public static Emperor getSingleton() {
if (singleton == null) {
synchronized (Emperor.class) {
if (singleton == null) {
singleton = new Emperor();
}
}
}
return singleton;
}
}
???????????ε???getSingleton????????????????????μ?????????????????????????????????????
??????????????A??е?singleton = new Emperor()??仰????????????????
????1????singleton ??????棻
????2??????Emperor()??????????????????????
????3????singleton ?????????????????
????????2??3?????????????????A???132???????????2??????B?????1????????????B?????null?????DCL?Ч????????????Ч??????JDK1.5???????????
volatile
public class Emperor {
private volatile static Emperor singleton;
//  ??е??????
private Emperor() {
}
//  ????????????????
public static Emperor getSingleton() {
if (singleton == null) {
synchronized (Emperor.class) {
if (singleton == null) {
singleton = new Emperor();
}
}
}
return singleton;
}
}
?????????????д??
??????t?????????????
//  ??????г????
private static class SingletonHolder{
private static final Emperor singleton = new Emperor();
}
//  ??е??????
private Emperor() {
}
//  ????????????????
public static Emperor getSingleton() {
return SingletonHolder.singleton;
}
????????????????????????????????????????ε???????????????????ε??÷??????????????
???????