第三种:用“双重检查加锁”,在getInstance中减少使用同步
public class Singleton {
private volatile static Singleton uniqueInstance = null;
public static void main(String[] args){
Singleton singleton = Singleton.getInstance();
}
public static Singleton getInstance(){
if (uniqueInstance == null){
synchronized (Singleton.class){
if (uniqueInstance == null){
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}