public class Singleton {
private static volatile Singleton singleton;
// volatile 相当于防止下面两个 == null 判断不被打乱
private Singleton() {}
public static Singleton getInstance() {
// 防止每次调用方法都上锁
if (singleton == null) {
synchronized (Singleton.class) {
//
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
单例模式-双重锁
最新推荐文章于 2024-02-21 19:06:10 发布