单例模式获取单例的时候判断单例是否为空两次的问题
if(heroFate == null){
synchronized (this){
if(Student == null){
student = new Student();
// 根据playerId 和 HeroId 从数据库中找出一条记录
Student student = select * fromt able where id = 1;
if(student != null){
}
}
}
}
public class Factory {
private volatile static Factory sInstance = null;
public static Factory getInstance() {
if (sInstance == null) {
synchronized (Factory.class) {
if (sInstance == null) {
sInstance = new Factory();
}
}
}
return sInstance;
}
}
为什么需要两次空判断?
原因是避免多线程并发的时候创建多余的实例。
第一次判断 sInstance是否为空是为了确保返回的实例不为空
第二次判断 sInstance是否为空是为了防止创建多余的实例
有两个线程获取这个单例的时候第一线程进来,先判断sInstance是否为空,为空加锁,判断sInstance,为空创建实例。当一个线程还在创建实例的时候第二个线程获取单例判断sInstance,为空等待,判断为不为空,不创建,返回上一个创建的实例。如果没有第二次判断的话第一个线程创建完释放锁的时候第二个线程获取锁并会再次创建实例。