单线程:
public static Object getInstant(){
if(mIntants == null){
mIntance = new Object();
}
return mIntance;
}
说明:单线程比较简单,只是需要保证第一次new对象,后续复用即可,常见于Application的单例
多线程:
在多线程情况下,如果2个线程同时加载,就肯能出现异常;
解决方案1:
构造时初始化,private static Object o = new Object;
public static Object getInstant(){
return o;
}
解决方案2:
使用同步:
pubic static synchoronized Object getInstant(){
if(mInstance == null){
mInstance = new Object();
}
return mInstance;
}
问题:每次获取都会触发同步,效率低下、
解决方案3:
双重检查:
private volidate static Object mInstance'
pubic static synchoronized Object getInstant(){
if(mInstance == null){
synchoronized(Object.class){
if(mInstance == null){
mInstance = new Object();
}
}
}
return mInstance;
}
说明:volidate声明当前变量其他线程也可见