懒汉式单例模式的线程安全实现(最新)

懒汉式单例模式是线程不安全的,这里有两个实现单例模式线程安全的方法(枚举方法不写了)

1.DCL双端锁

通过volatile禁止指令重排,防止得到null

public class Study {
   private volatile static Study instance;

   private void Study(){
   }

   public static Study getInstance(){
       if (instance == null){
           synchronized (Study.class){
               if (instance == null){
                   instance = new Study();
               }
           }
       }
       return instance;
   }

}

2.静态内部类

public class Study {
   private void Study(){

   }
   public static class Study2{
       private static Study instance = new Study();
   }

   public static Study getInstance(){
       return Study2.instance;
   }
}

·

上一篇:组件


下一篇:内核与内核模块