DDL 懒汉式


/**
 * @Author: wz
 * @Date: 2022/7/11 22:07
 */
public class LazyMan {



    /**
     * 懒汉式
     * DCL 懒汉式
     */
    private LazyMan(){
        System.out.println(Thread.currentThread().getName()+"-----"+"ok");
    }
    // volatile 保证可见性 不让指令从重排
    private static volatile LazyMan lazyMan;

    public static LazyMan getInstance(){
        if(null==lazyMan){
            synchronized (LazyMan.class){
                if(null==lazyMan){
                    lazyMan= new LazyMan(); // 不是一个原子性的
                    // 1、分配内存空间
                    // 2、执行构造方法,初始化对象
                    // 3、把空间指向对象
                }
            }
        }
       return lazyMan;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 101; i++) {
            new Thread(()->{
                LazyMan.getInstance();
            }).start();
        }
    }


}

你可能感兴趣的:(DDL 懒汉式)