publicstatic Mgr02 getInstance(){ if (INSTANCE == null) { synchronized (Mgr02.class){ if (INSTANCE == null ){ INSTANCE = new Mgr02(); } } } return INSTANCE; } publicvoidm(){ System.out.println("m"); }
publicstaticvoidmain(String[] args){ for (int i = 0; i < 100; i++) { new Thread(()->{ System.out.println(Mgr02.getInstance().hashCode()); }).start(); } } }
为了保证线程安全,写法相对饿汉式麻烦,但是只有在使用时才会实例化
静态内部类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
publicclassMgr03{ privateMgr03(){} privatestaticclassMgr03Holder{ privatestaticfinal Mgr03 INSTANCE = new Mgr03(); } publicstatic Mgr03 getInstance(){ return Mgr03Holder.INSTANCE; } publicstaticvoidmain(String[] args){ for (int i = 0; i < 100; i++) { new Thread(()->{ System.out.println(Mgr03.getInstance().hashCode()); }).start(); } } }
与饿汉式类似,都是由 JVM 保证线程安全,但静态内部类是延迟加载
枚举
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
publicenum Mgr04 { INSTANCE; publicvoidm(){ System.out.println("m"); } publicstaticvoidmain(String[] args){ for (int i = 0; i < 100; i++) { new Thread(()->{ System.out.println(Mgr04.INSTANCE.hashCode()); }).start(); } } }