简单且线程安全的两个单例模式java程序

[java] view plaincopy
  1. package com.work.pattern;  
  2.   
  3.   
  4.   
  5. public class Singleton2 {  
  6.   
  7.     private static  Singleton2 instance = new Singleton2();  
  8.   
  9.     private Singleton2(){  
  10.   
  11.           
  12.   
  13.     }  
  14.   
  15.     public static Singleton2 getInstance(){  
  16.   
  17.         return instance;  
  18.   
  19.     }  
  20.   
  21. }  

================单例模式二====================================

[java] view plaincopy
  1. package com.work.pattern;  
  2.   
  3.   
  4.   
  5. /** 
  6.  
  7.  * 单例模式创新!google的ioc作者写的。只有在调用的时候才会初始化!而且线程安全 
  8.  
  9.  * 超级牛! 
  10.  
  11.  * @author wmj 
  12.  
  13.  * 
  14.  
  15.  */  
  16.   
  17. public class Singleton {  
  18.   
  19.   
  20.   
  21.     static class SingletonHolder {  
  22.   
  23.         static Singleton instance = new Singleton();  
  24.   
  25.     }  
  26.   
  27.   
  28.   
  29.     public static Singleton getInstance() {  
  30.   
  31.         return SingletonHolder.instance;  
  32.   
  33.     }  
  34.   
  35.   
  36.   
  37. }  
原文地址:https://www.cnblogs.com/hzcya1995/p/13318004.html