懒汉模式:延迟加载,只有在真正使用的时候才开始实例化。
    但是懒汉模式可能会存在以下问题:

    • 线程安全问题
    • 加锁优化
    • 编译器(JIT)、CPU有可能对指令进行重排序,导致使用到尚未初始化的实例,可以通过添加volatile关键字进行修饰,volatile可以防止指令重排序

    下面上代码

    1. /**
    2. * @author xzf
    3. * @create 2021-02-08 8:40
    4. */
    5. public class LazySingleton {
    6. private volatile static LazySingleton instance = null;
    7. private LazySingleton(){}
    8. public static LazySingleton getInstance(){
    9. if (instance == null) {
    10. synchronized (LazySingleton.class){
    11. if(instance == null){
    12. instance = new LazySingleton();
    13. }
    14. }
    15. }
    16. return instance;
    17. }
    18. }