单例模式的3种实现方式, 及其性能对比
1. 懒汉模式(double check), 线程安全, 效率不高, 可以延迟加载 public class Singleton1 implements Serializable { // 用volatile修饰instance, 禁止指令重排序, 为保证多线程安全 private volatile static Singleton1 instance = null; private Singleton1() { // 防止反射调用私有构造方法(跳过安全检查), 重复实例化实例 if (instance != null) { throw new RuntimeException("error:instance=" + instance); } } public static Singleton1 getInstance() { if (instance == null) { synchronized (Singleton1.class) { if (instance == null) { instance = new Singleton1(); } } } return instance; } private Object readResolve() { return instance; // 防止反序列化重复实例化实例 } } 2. 饿汉模式, 线程安全, 效率高,