单例模式 下的线程锁问题

xiaoxiao2021-02-28  146

package com.demo; /* * 单例模式 * 下的线程锁问题 */ public class SingleTHreadLock { } // ----------懒汉式(迟加载) class Single1 { private static Single1 s = null; private Single1() { } // -------------------------使用同步函数的方式,效率比较低,因为同步外的线程每一次都需要判断锁 public static synchronized Single1 getInstance1() { if (s == null) { s = new Single1(); } return s; } // ----------------------使用双重判断,效率更高 public static Single1 getInstance2() { if (s == null) { synchronized (Single1.class) { if (s == null) { s = new Single1(); } } } return s; } } // -----------饿汉式 class Single2 { private static Single2 s = new Single2(); private Single2() { } public Single2 getInstance() { return s; } }
转载请注明原文地址: https://www.6miu.com/read-22043.html

最新回复(0)