多线程下单例模式示例(synchronized,DCL,volatile)
//加锁、保证线程安全的单例模式(重量级)
class SingleDemo { public static SingleDemo instance = null; private SingleDemo() { System.out.println(Thread.currentThread().getName() + "\t 我是SingleDemo构造方法"); } public static synchronized SingleDemo getInstance() { if (instance == null) { instance = new SingleDemo(); } return instance; } }
//DCL(双端检索)机制不一定线程安全,原因是有指令重排,加入volatile可以禁止指令重排
//指令重排可能导致线程不安全
public static SingleDemo getInstance() { if (instance == null) { //DCL(双端检索)机制 synchronized (SingleDemo.class) { if (instance == null) { instance = new SingleDemo(); } } } return instance; }
//DCL(Double check lock) + volatile 单例模式 (轻量级)
class SingleDemo { public static volatile SingleDemo instance = null; private SingleDemo() { System.out.println(Thread.currentThread().getName() + "\t 我是SingleDemo构造方法"); } public static SingleDemo getInstance() { if (instance == null) { //DCL(双端检索)机制 synchronized (SingleDemo.class) { if (instance == null) { instance = new SingleDemo(); } } } return instance; } }
public class Main { public static void main(String[] args) { for (int i = 0; i < 5; i++) { new Thread(() -> { SingleDemo.getInstance(); }, String.valueOf(i)).start(); } } }