gongruitao 2020-01-04
package savesingleton; /* 使用同步将单例模式中的懒汉式改写成线程安全的 @author zsben @create 2020-01-03 22:22 */ class Bank{ private Bank(){} private static Bank instance = null; /*public static synchronized Bank getInstance(){ if(instance == null){ instance = new Bank(); } return instance; }较为低效 */ //高效办法:内外各判一次 public static Bank getInstance(){ if(instance == null){ //里面一定要再判一次:想想为什么,再加一层是为了防止有多个线程同时进入,所以内层再加一层 synchronized (Bank.class) { if(instance == null) { instance = new Bank(); } } } return instance; } }