标签:线程安全 let 情况 null 串行 空指针异常 vol get vat
缺点:不能懒加载
// 不能懒加载
public class SingletonObject1 {
private static final SingletonObject1 instance = new SingletonObject1();
private SingletonObject1(){
}
public static SingletonObject1 getInstance(){
return instance;
}
}
public class SingletonObject2 {
private static SingletonObject2 instance = null;
private SingletonObject2(){
}
public static SingletonObject2 getInstance(){
// 线程不安全模式
if (instance == null)
instance = new SingletonObject2();
return SingletonObject2.instance;
}
}
public class SingletonObject3 {
private static SingletonObject3 instance = null;
private SingletonObject3(){
}
// 串行执行,效率低下
public static synchronized SingletonObject3 getInstance(){
if (instance == null)
instance = new SingletonObject3();
return SingletonObject3.instance;
}
}
public class SingletonObject4 {
private static SingletonObject4 instance = null;
private SingletonObject4(){
}
// 双重检查机制,严格单例,解决了懒加载的问题,但是也带来了问题:空指针异常
public static SingletonObject4 getInstance(){
if (instance == null){
synchronized (SingletonObject4.class){
if (instance == null)
instance = new SingletonObject4();
}
}
return SingletonObject4.instance;
}
}
public class SingletonObject5 {
private static volatile SingletonObject5 instance = null;
private SingletonObject5(){
}
// 双重检查机制,严格单例,解决了懒加载的问题,但是也带来了问题:空指针异常
public static SingletonObject5 getInstance(){
if (instance == null){
synchronized (SingletonObject5.class){
if (instance == null)
instance = new SingletonObject5();
}
}
return SingletonObject5.instance;
}
}
public class SingletonObject6 {
private SingletonObject6(){
}
private static class InstanceHolder{
private final static SingletonObject6 instance = new SingletonObject6();
}
public static SingletonObject6 getInstance(){
return InstanceHolder.instance;
}
}
标签:线程安全 let 情况 null 串行 空指针异常 vol get vat
原文地址:https://www.cnblogs.com/ch-forever/p/10752193.html