目录
懒汉式
public class Singleton {
private Singleton(){
}
private static Singleton singleton = null;
public static Singleton getSingleton(){
if(singleton == null){
singletion = new Singleton();
}
return singleton;
}
}
上述懒汉式会有线程安全问题
优化
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;
}
}