线程安全单例
双重检查锁定(DCL)
public class Singleton {
// volatile保证可见性和禁止指令重排
private static volatile Singleton instance;
public static Singleton getInstance() {
if (instance == null) { // 第一次检查 不加锁直接读,效率高
synchronized (Singleton.class) { // 加锁后再次检查,避免多个线程同时创建实例
if (instance == null) { // 第二次检查
instance = new Singleton();
}
}
}
return instance;
}
}
2025年7月27日大约 8 分钟