1 package bytezero.deadlock; 2 3 /** 4 * 使用同步机制讲单例模式中的懒汉式改写为线程安全的 5 * 6 * 7 * 8 * 9 * @author Bytezero1·zhenglei! Email:420498246@qq.com 10 * create 2021-10-18 8:57 11 */ 12 public class BankTest { 13 } 14 class Bank{ 15 16 private Bank(){ 17 18 } 19 private static Bank instance = null; 20 21 public static Bank getInstance(){ 22 23 //方式一:效率稍差 24 // synchronized (Bank.class) { 25 // if(instance == null){ 26 // instance = new Bank(); 27 // } 28 // return instance; 29 // } 30 //方式二 : 效率更高 31 if(instance == null){ 32 33 synchronized (Bank.class) { 34 if(instance == null){ 35 instance = new Bank(); 36 } 37 38 } 39 } 40 return instance; 41 } 42 }