package com.msb.singleton; import java.util.Objects; /** * @Author bingor * @Date 2022-10-06 10:25 * @Description: * 懒汉式: * 虽然达到了按需初始化的目的,但却带来了线程不安全的问题 * 可以通过synchronized解决,但也带来了效率下降 * @Version: 1.0 */ public class Singleton06 { private static Singleton06 INSTANCE; private Singleton06() {} public static Singleton06 getInstance() { if(Objects.isNull(INSTANCE)) { //试图减少同步代码块的方式来提高效率,然而不可行,仍然会有线程不安全问题 synchronized (Singleton06.class) { if(Objects.isNull(INSTANCE)) { try { //这里是为了测试线程 Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } INSTANCE = new Singleton06(); } } } return INSTANCE; } public static void main(String[] args) { for (int i=0; i<100; i++) { new Thread(() -> { //同样的哈希码,可能是不同的对象。但不同的对象,有不同的哈希码 System.out.println(Singleton06.getInstance().hashCode()); }).start(); } } }