在单例模式的懒汉式中会出现线程不安全的情况,可使用以下两种方法解决:
方法一:同步函数:
代码:
1 private static Bank instance = null; 2 3 public static synchronized Bank getInstance() {//解决线程不安全问题(法一) 4 if (instance == null) { 5 instance = new Bank(); 6 } 7 return instance; 8 }
方法二:同步代码块
1 public static Bank getInstance1() {//方法二(效率稍差:会产生大量线程的无效排队) 2 synchronized (Bank.class) { 3 if (instance == null) { 4 instance = new Bank(); 5 } 6 return instance; 7 } 8 } 9 10 //改进方法二(去除无效排队的问题) 11 public static Bank getInstance2() { 12 if (instance == null) { 13 synchronized (Bank.class) { 14 if (instance == null) { 15 instance = new Bank(); 16 } 17 } 18 } 19 return instance; 20 }