Java 写一个线程安全的单例模式(饱汉/饿汉)
饿汉单例
public class Singleton {
private static Singleton singleton = new Singleton();
private Singleton() {}
public static Singleton createInstance() {
return singleton;
}
}
饱汉单例
public class Singleton {
private static volatile Singleton baoHan;
private Singleton() {
}
// double check 双重判断检查锁
public static Singleton createInstance() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}