懒汉式【单例模式】
public class Singleton{
private Singleton(){
}
//保证可见性,防止指令重排
private volatile static Singleton singleton = null;
public static Singleton getSingleton(){
//提升效率,对象已经存在就不再加锁判断
if(singleton == null){
//加同步锁
synchronized (Singleton.class){
//检查对象是否存在,不存在创建对象
if(singleton == null){
singleton = new Singleton();
}
}
}
return singleton;
}
}