- 代码
public class SingleInstance {
private volatile static SingleInstance uniqueInstance = null;
public static SingleInstance getInstance() {
if (uniqueInstance == null) {
synchronized (SingleInstance.class) {
if (uniqueInstance == null) {
uniqueInstance = new SingleInstance();
}
}
}
return uniqueInstance;
}
}
问题: 为啥这里出现两句if (uniqueInstance == null) {}?
假设一个场景,当对象没被创建的时候,来了10个线程请求uniqueInstance,判断为null后,排队获取锁,当第一个拿到锁的线程创建了对象之后,又来了10个线程,这些线程就不用去等待锁了,直接判断出uniqueInstance!=null,返回实例就完了。