// 线程安全的懒汉式单例
public class Singleton {
//使用volatile关键字防止重排序,因为 new Instance()是一个非原子操作,可能创建一个不完整的实例
private static volatile Singleton singleton;
private Singleton() {}
public static Singleton getSingleton() {
// Double-Check idiom
if (singleton == null) {
synchronized (Singleton.class) { // 1
// 只需在第一次创建实例时才同步
if (singleton == null) { // 2
singleton = new Singleton(); // 3
}
}
}
return singleton;
}
}
单例模式与双重检查(Double-Check idiom)
最新推荐文章于 2022-06-18 15:27:09 发布