package GOGO; /** * 并发下的单例模式: * 双端检索机制DCL(Double check Lock),但是可能会导致指令重排!!!!!线程不一定安全,依旧存在单例模式的隐患 * 可以加入volatile禁止指令重排 */ public class SingletonDemo { private static volatile SingletonDemo instance = null;//禁止创建对象时指令重排!!!!!!!!! //构造器独一份 private SingletonDemo(){ //如果只有一个实例,该句话只被打印一次 System.out.println(Thread.currentThread().getName()+"\t 我是构造方法"); } //双端检索机制DCL(Double check Lock),但是可能会导致指令重排!!!!!线程不一定安全,依旧存在单例模式的隐患,概率很低 public static SingletonDemo getInstance(){ if (instance == null) synchronized (SingletonDemo.class) {//枷锁 if (instance == null) instance = new SingletonDemo(); } return instance; } public static void main(String[] args) { // //单线程 // System.out.println(SingletonDemo.getInstance() == SingletonDemo.getInstance()); // System.out.println(SingletonDemo.getInstance() == SingletonDemo.getInstance()); // System.out.println(SingletonDemo.getInstance() == SingletonDemo.getInstance()); System.out.println("======================="); //并发多线程,就会出现很多问题,会创建很多实例,可以对getInstance加synchronized,但是太重,并发效率降低 for (int i = 1; i < 10; i++) { new Thread(()->{ SingletonDemo.getInstance(); },String.valueOf(i)).start(); } } }
并发下的单例模式完整解决方案
最新推荐文章于 2022-11-02 21:15:00 发布