标签:turn class 出现 lis null ret volatil on() 判断
目录
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;
private SingletonObject2(){}
public static SingletonObject2 getInstance() {
if (null == instance){
instance = new SingletonObject2();
}
return instance;
}
}
/**
将整个方法锁住,效率有待优化
*/
public class SingletonObject3 {
private static SingletonObject3 instance;
private SingletonObject3(){}
public synchronized static SingletonObject3 getInstance() {
if (null == instance){
instance = new SingletonObject3();
}
return instance;
}
}
/**
* Double Check
* 可能会导致空指针异常:
*/
public class SingletonObject4 {
private static SingletonObject4 instance;
private SingletonObject4(){}
public static SingletonObject4 getInstance() {
if (null == instance){
synchronized (SingletonObject4.class){
if (null == instance) {
instance = new SingletonObject4();
}
}
}
return instance;
}
}
public class SingletonObject5 {
//volatile 保证读的过程,写必须完成,
// 也就new SingletonObject5的时候里面的内容全部构造完成
private volatile static SingletonObject5 instance;
private SingletonObject5(){}
public static SingletonObject5 getInstance() {
if (null == instance){
synchronized (SingletonObject5.class){
if (null == instance) { //这里一定需要再次判断
instance = new SingletonObject5();
}
}
}
return instance;
}
}
public class SingletonObject6 {
private SingletonObject6() {}
private static class InstanceHolder {
private final static SingletonObject6 instance = new SingletonObject6();
}
public static SingletonObject6 getInstance() {
return InstanceHolder.instance;
}
}
public class SingletonObject7 {
private SingletonObject7(){ }
private enum Singleton {
INSTANCE;
private final SingletonObject7 instance;
Singleton() {
instance = new SingletonObject7();
}
public SingletonObject7 getInstance() {
return instance;
}
}
public static SingletonObject7 getInstance() {
return Singleton.INSTANCE.getInstance();
}
}
标签:turn class 出现 lis null ret volatil on() 判断
原文地址:https://www.cnblogs.com/liuligang/p/10593478.html