java基础——线程安全的单例模式懒汉式
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; } }
相关推荐
fraternityjava 2020-06-14
ahnuzfm 2020-05-07
gongruitao 2020-05-02
xiaoemo0 2020-04-08
付春杰Blog 2020-03-26
Kele0 2020-05-30
elizabethxxy 2020-04-27
JF0 2020-03-20
ahnuzfm 2020-02-03
Ingram 2020-01-16
缘起宇轩阁 2019-12-30
zuixin 2020-01-03
pengkunstone 2019-12-27
waitui00 2019-12-22