package single; /** * @author : lijie * @Description: 懒汉式单例 * @date Date : 2021年08月23日 8:45 */ public class Hungry { private Hungry() { System.out.println(Thread.currentThread().getName()+"--OK"); } private volatile static Hungry hungry; // 双重锁检测机制的 懒汉式单例 DCL懒汉式 public static Hungry getInstance() { if (hungry == null) { synchronized (Hungry.class) { if (hungry == null) { // 不是一个原子性的操作 // 1.分配内存空间 // 2.执行构造方法,初始化对象 // 3.把这个对象指向这个空间 // 有可能123或者132 所以要采用volatile禁止指令重排 hungry = new Hungry(); } } } return hungry; } public static void main(String[] args) { for (int i = 0; i < 10; i++) { new Thread(()->Hungry.getInstance()).start(); } } }
原文:https://www.cnblogs.com/codehero/p/15174426.html