正常情况下的懒汉式
private static LazySingle instance = null;
public static LazySingle getInstance() {
if (instance == null) {
instance = new LazySingle();
}
return instance;
}
这里很好理解, 如果没有实例对象就创建一个, 如果已经存在该实例对象, 就直接返回该对象.
但这在多线程环境下会有线程安全问题, 比如线程A和B同时去调用getInstance()方法, 由于没有队列关系, 两个线程同时认为没有实例对象存在, 这样最终会导致两个线程分别创建了一个对象.
package singletest;
/**
* @Date:2022/1/8 9:56
* @Author:NANDI_GUO
*/
public class LazySingle {
private int count;
private LazySingle() {
count++;
System.out.println(Thread.currentThread().getName()+"创建了对象"+count+"次");
}
private static LazySingle instance = null;
public static LazySingle getInstance() {
if (instance == null) {
instance = new LazySingle();
}
return instance;
}
public static void main(String[] args) {
for (int i = 0; i < 2; i++) {
new Thread(new Runnable() {
@Override
public void run() {
LazySingle.getInstance();
}
}).start();
}
}
}
============================================================
输出:
Thread-0创建了对象1次
Thread-1创建了对象1次
解决办法1, 在实例化的getInstance()方法上加锁
private static LazySingle instance = null;
public static synchronized LazySingle getInstance() {
if (instance == null) {
instance = new LazySingle();
}
return instance;
}
=================================================
输出:
Thread-0创建了对象1次
但这样的话, 极大的影响了运行效率. 所有线程在进入该方法时都需要排队等锁了
解决办法2, 双检索模式
private static LazySingle instance = null;
public static volatile LazySingle getInstance() {
if (instance == null) {
synchronized(LazySingle.class) {
if (instance == null) {
instance = new LazySingle();
}
}
}
return instance;
}
主要是, 两次判空, 所有线程判空之后,排队等待获得锁, 只要有一个线程获得锁后, instance就不再为空, 那么剩下在等待的线程就不再会等待锁,直接结束了.