单例-线程安全

来源:互联网 发布:美国 量子计算机 知乎 编辑:程序博客网 时间:2024/05/20 01:35
  1. /** 
  2.  * 懒汉式线程安全方法二 
  3.  */  
  4. public class ThreadSafeSingleInstance {  
  5.   
  6.     // 私有的静态实例  
  7.     private static ThreadSafeSingleInstance instance;  
  8.       
  9.     // 私有的构造方法  
  10.     private ThreadSafeSingleInstance(){};  
  11.       
  12.     /** 
  13.      * 同步块保护加二次判断 
  14.      * 解决问题 
  15.      */  
  16.     public static ThreadSafeSingleInstance getInstance() throws InterruptedException {  
  17.         if (instance == null) {  
  18.             // 进方法后进行实例判断,若实例为空,进入同步块  
  19.             // 多线程时,多个线程会同时进入到同步块外面等待  
  20.             // 此时,一个线程拿到ThreadSafeSingleInstance.class 后,其他线程在synchronized块外面等待  
  21.             // 待锁释放时,一个等待的线程拿到锁,同时再次检查实例是否为空  
  22.             // 并决定是否要创建实例  
  23.             synchronized (String.class) {//ThreadSafeSingleInstance.class) {  
  24.                 Thread.sleep(1000);  
  25.                 if (instance == null) {  
  26.                     instance = new ThreadSafeSingleInstance();  
  27.                 }  
  28.             }  
  29.         }  
  30.           
  31.         return instance;  
  32.     }  
  33.       

  1. }  
  1. /** 
  2.  * 饿汉式 
  3.  */  
  4. public class HungrySingleInstance {  
  5.   
  6.     // 私有的构造方法  
  7.     private HungrySingleInstance(){};  
  8.       
  9.     // 静态类变量,初始化类时变创建对象  
  10.     private static HungrySingleInstance instance = new HungrySingleInstance();  
  11.       
  12.     // 或采用静态块形式初始化instance  
  13.     static {  
  14.         instance = new HungrySingleInstance();  
  15.     }  
  16.       
  17.     /** 
  18.      * 获取实例方法 
  19.      * 优点: 
  20.      * 线程安全,且不存在懒汉式的二次判断问题 
  21.      * 缺点: 
  22.      * 初始化即new 实例对象出来,违背资源利用习惯(即不管用不用都初始化实例出来) 
  23.      * @return 
  24.      */  
  25.     public static HungrySingleInstance getInstance() {  
  26.         return instance;  
  27.     }  
  28. }  

0 0
原创粉丝点击