标签:== turn 方法 异常 stat 加载 let 初始 排序
public class HungerySingleton {
private HungerySingleton() {};
private static HungerySingleton instance=new HungerySingleton();
public static HungerySingleton getInstance() {
return instance;
}
}
在加载的时候已经被实例化,只有一次,线程安全
但如果一直不使用,占用资源
public class HoonSingleton {
private HoonSingleton() {};
private static HoonSingleton instance;
public synchronized static HoonSingleton getInstance() {
if (null==instance) {
instance=new HoonSingleton();
}
return instance;
}
}
public class DCLSingleton {
private DCLSingleton() {};
private volatile static DCLSingleton instance=null;
public static DCLSingleton getInstance() {
if (null==instance) {
synchronized (DCLSingleton.class) {
if (null==instance) {
instance=new DCLSingleton();
}
}
}
return instance;
}
}
public class HolderSingleton {
private HolderSingleton() {};
//原理:内部类在加载的时候不会初始化内部的变量,只有在用到的时候才会进行初始化,而且由jvm保证了线程安全
private static class Holder{
private static HolderSingleton instance=new HolderSingleton();
}
public static HolderSingleton getInstance() {
return Holder.instance;
}
}
public enum EnumSingleton {
//枚举有类加载后就直接初始化,相对于饿汉式
INSTANCE;
public static EnumSingleton getInstance() {
return INSTANCE;
}
}
public class EnumHolderSingleton {
private EnumHolderSingleton() {}
public static EnumHolderSingleton getInstance() {
return EnumHolder.instance;
}
//依靠内部类延迟加载的功能实现懒汉式单例
private enum EnumHolder{
INSTANCE;
private static EnumHolderSingleton instance=new EnumHolderSingleton();
}
}
标签:== turn 方法 异常 stat 加载 let 初始 排序
原文地址:https://www.cnblogs.com/lifeone/p/11653140.html