单例模式实现

  1. 静态内部类(static nested class) 优先考虑
  2.  
  3. public class LazySingleton{  
  4.     private LazySingleton(){}  
  5.   
  6.     private static class Nested{  
  7.         private static final LazySingleton single = new LazySingleton();  
  8.     }  
  9.   
  10.     public static LazySingleton getInstance(){  
  11.         return Nested.single;  
  12.     }  
  13. }  

双重检查锁定(DCL)

  1. public class LazySingleton{  
  2.     private LazySingleton(){}  
  3.   
  4.     private static volatile LazySingleton single = null;  
  5.   
  6.     public static LazySingleton getInstance(){  
  7.         if(single == null){  
  8.             synchronized (LazySingleton.class){  
  9.                 if(single == null){  
  10.                     single = new LazySingleton();   //① 非原子操作  
  11.                 }  
  12.             }  
  13.         }   
  14.         return single;  
  15.     }  
  16. }  
原文地址:https://www.cnblogs.com/sjqq/p/7486807.html