線程安全的兩種方式:雙重校驗鎖和靜態(tài)內(nèi)部類祟昭,推薦使用靜態(tài)內(nèi)部類的方式
1、雙重校驗鎖
public class SingletonDemo7 {
? ? private volatile static SingletonDemo7 singletonDemo7;
? ? private SingletonDemo7(){}
? ? public static SingletonDemo7 getSingletonDemo7(){
? ? ? ? if(singletonDemo7 ==null) {
? ? ? ? ? ? synchronized(SingletonDemo7.class) {
? ? ? ? ? ? ? ? if(singletonDemo7 ==null) {
? ? ? ? ? ? ? ? ? ? singletonDemo7 = new SingletonDemo7();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return singletonDemo7;
? ? }
}
2、靜態(tài)內(nèi)部類
publicclass SingletonDemo5 {
? ? private static class SingletonHolder{
? ? ? ? private static final SingletonDemo5 instance =new SingletonDemo5();
? ? }
? ? private SingletonDemo5(){}
? ? public static final SingletonDemo5 getInsatance(){
? ? ? ? return SingletonHolder.instance;
? ? }
}