“J.U.C”:Condition

来源:互联网 发布:中药大词典软件 编辑:程序博客网 时间:2024/06/18 00:23

在看Condition之前,我们先来看下面这个例子:

工厂类,用来存放、取出商品:

[java] view plain copy
  1. public class Depot {  
  2.     private int depotSize;     //仓库大小  
  3.     private Lock lock;         //独占锁  
  4.       
  5.     public Depot(){  
  6.         depotSize = 0;  
  7.         lock = new ReentrantLock();  
  8.     }  
  9.       
  10.     /** 
  11.      * 商品入库 
  12.      * @param value 
  13.      */  
  14.     public void put(int value){  
  15.         try {  
  16.             lock.lock();  
  17.             depotSize += value;  
  18.             System.out.println(Thread.currentThread().getName() + " put " + value +" ----> the depotSize: " + depotSize);  
  19.         } finally{  
  20.             lock.unlock();  
  21.         }  
  22.     }  
  23.       
  24.     /** 
  25.      * 商品出库 
  26.      * @param value 
  27.      */  
  28.     public void get(int value){  
  29.         try {  
  30.             lock.lock();  
  31.             depotSize -= value;  
  32.             System.out.println(Thread.currentThread().getName() + " get " + value +" ----> the depotSize: " + depotSize);  
  33.         } finally{  
  34.             lock.unlock();  
  35.         }  
  36.     }  
  37. }  

生产者,生产商品,往仓库里面添加商品:

[java] view plain copy
  1. public class Producer {  
  2.     private Depot depot;  
  3.       
  4.     public Producer(Depot depot){  
  5.         this.depot = depot;  
  6.     }  
  7.       
  8.     public void produce(final int value){  
  9.         new Thread(){  
  10.             public void run(){  
  11.                 depot.put(value);  
  12.             }  
  13.         }.start();  
  14.     }  
  15. }  

消费者,消费商品,从仓库里面取出商品:

[java] view plain copy
  1. public class Customer {  
  2.     private Depot depot;  
  3.       
  4.     public Customer(Depot depot){  
  5.         this.depot = depot;  
  6.     }  
  7.       
  8.     public void consume(final int value){  
  9.         new Thread(){  
  10.             public void run(){  
  11.                 depot.get(value);  
  12.             }  
  13.         }.start();  
  14.     }  
  15. }  

测试类:

[java] view plain copy
  1. public class Test {  
  2.     public static void main(String[] args) {  
  3.         Depot depot = new Depot();  
  4.           
  5.         Producer producer = new Producer(depot);  
  6.         Customer customer = new Customer(depot);  
  7.           
  8.         producer.produce(10);  
  9.         customer.consume(5);  
  10.         producer.produce(20);  
  11.         producer.produce(5);  
  12.         customer.consume(35);  
  13.     }  
  14. }  

运行结果:

[java] view plain copy
  1. Thread-0 put 10 ----> the depotSize: 10  
  2. Thread-1 get 5 ----> the depotSize: 5  
  3. Thread-2 put 20 ----> the depotSize: 25  
  4. Thread-3 put 5 ----> the depotSize: 30  
  5. Thread-4 get 35 ----> the depotSize: -5  

程序的运行结果是没有错误的,先put10、然后get5、put20、put5、get35。程序运行结果非常正确,但是在现实生活中,这个实例存在两处错误:

第一:仓库的容量是有限的,我们不可能无限制的往仓库里面添加商品。

第二:仓库的容量是不可能为负数的,但是最后的结果为-5,与现实存在冲突。

针对于上面两处错误,怎么解决?这就轮到Condition大显神通了。

Condition

通过前面几篇博客我们知道Lock提供了比synchronized更加强大、灵活的锁机制,它从某种程度上来说替代了synchronized方式的使用。Condition从字面上面理解就是条件。对于线程而言它为线程提供了一个含义,以便在某种状态(条件Condition)可能为true的另一个线程通知它之前,一直挂起该线程。

对于Condition,JDK API中是这样解释的:

Condition 将 Object 监视器方法(wait、notify 和 notifyAll)分解成截然不同的对象,以便通过将这些对象与任意 Lock 实现组合使用,为每个对象提供多个等待 set(wait-set)。其中,Lock 替代了 synchronized 方法和语句的使用,Condition 替代了 Object 监视器方法的使用。

条件(也称为条件队列 或条件变量)为线程提供了一个含义,以便在某个状态条件现在可能为 true 的另一个线程通知它之前,一直挂起该线程(即让其“等待”)。因为访问此共享状态信息发生在不同的线程中,所以它必须受保护,因此要将某种形式的锁与该条件相关联。等待提供一个条件的主要属性是:以原子方式 释放相关的锁,并挂起当前线程,就像 Object.wait 做的那样。

Condition 实例实质上被绑定到一个锁上。要为特定 Lock 实例获得 Condition 实例,请使用其newCondition() 方法。下面我们通过Condition来解决上面的问题:这里只改仓库Depot的代码:

[html] view plain copy
  1. public class Depot {  
  2.     private int depotSize;     //仓库大小  
  3.     private Lock lock;         //独占锁      
  4.     private int capaity;       //仓库容量  
  5.       
  6.     private Condition fullCondition;          
  7.     private Condition emptyCondition;  
  8.       
  9.     public Depot(){  
  10.         this.depotSize = 0;  
  11.         this.lock = new ReentrantLock();  
  12.         this.capaity = 15;  
  13.         this.fullCondition = lock.newCondition();  
  14.         this.emptyCondition = lock.newCondition();  
  15.     }  
  16.       
  17.     /**  
  18.      * 商品入库  
  19.      * @param value  
  20.      */  
  21.     public void put(int value){  
  22.         lock.lock();  
  23.         try {  
  24.             int left = value;  
  25.             while(left > 0){  
  26.                 //库存已满时,“生产者”等待“消费者”消费  
  27.                 while(depotSize >= capaity){  
  28.                     fullCondition.await();  
  29.                 }  
  30.                 //获取实际入库数量:预计库存(仓库现有库存 + 生产数量) > 仓库容量   ? 仓库容量 - 仓库现有库存     :    生产数量  
  31.                 //                  depotSize   left   capaity  capaity - depotSize     left  
  32.                 int inc = depotSize + left > capaity ? capaity - depotSize : left;   
  33.                 depotSize += inc;  
  34.                 left -inc;  
  35.                 System.out.println(Thread.currentThread().getName() + "----要入库数量: " + value +";;实际入库数量:" + inc + ";;仓库货物数量:" + depotSize + ";;没有入库数量:" + left);  
  36.               
  37.                 //通知消费者可以消费了  
  38.                 emptyCondition.signal();  
  39.             }  
  40.         } catch (InterruptedException e) {  
  41.         } finally{  
  42.             lock.unlock();  
  43.         }  
  44.     }  
  45.       
  46.     /**  
  47.      * 商品出库  
  48.      * @param value  
  49.      */  
  50.     public void get(int value){  
  51.         lock.lock();  
  52.         try {  
  53.             int left = value;  
  54.             while(left > 0){  
  55.                 //仓库已空,“消费者”等待“生产者”生产货物  
  56.                 while(depotSize <= 0){  
  57.                     emptyCondition.await();  
  58.                 }  
  59.                 //实际消费      仓库库存数量     < 要消费的数量     ?   仓库库存数量     : 要消费的数量  
  60.                 int dec = depotSize < left ? depotSize : left;  
  61.                 depotSize -dec;  
  62.                 left -dec;  
  63.                 System.out.println(Thread.currentThread().getName() + "----要消费的数量:" + value +";;实际消费的数量: " + dec + ";;仓库现存数量:" + depotSize + ";;有多少件商品没有消费:" + left);  
  64.               
  65.                 //通知生产者可以生产了  
  66.                 fullCondition.signal();  
  67.             }  
  68.         } catch (InterruptedException e) {  
  69.             e.printStackTrace();  
  70.         } finally{  
  71.             lock.unlock();  
  72.         }  
  73.     }  
  74. }  

test:

[java] view plain copy
  1. public class Test {  
  2.     public static void main(String[] args) {  
  3.         Depot depot = new Depot();  
  4.           
  5.         Producer producer = new Producer(depot);  
  6.         Customer customer = new Customer(depot);  
  7.           
  8.         producer.produce(10);  
  9.         customer.consume(5);  
  10.         producer.produce(15);  
  11.         customer.consume(10);  
  12.         customer.consume(15);  
  13.         producer.produce(10);  
  14.     }  
  15. }  

运行结果:

[java] view plain copy
  1. Thread-0----要入库数量: 10;;实际入库数量:10;;仓库货物数量:10;;没有入库数量:0  
  2. Thread-1----要消费的数量:5;;实际消费的数量: 5;;仓库现存数量:5;;有多少件商品没有消费:0  
  3. Thread-4----要消费的数量:15;;实际消费的数量: 5;;仓库现存数量:0;;有多少件商品没有消费:10  
  4. Thread-2----要入库数量: 15;;实际入库数量:15;;仓库货物数量:15;;没有入库数量:0  
  5. Thread-4----要消费的数量:15;;实际消费的数量: 10;;仓库现存数量:5;;有多少件商品没有消费:0  
  6. Thread-5----要入库数量: 10;;实际入库数量:10;;仓库货物数量:15;;没有入库数量:0  
  7. Thread-3----要消费的数量:10;;实际消费的数量: 10;;仓库现存数量:5;;有多少件商品没有消费:0  

在Condition中,用await()替换wait(),用signal()替换 notify(),用signalAll()替换notifyAll(),对于我们以前使用传统的Object方法,Condition都能够给予实现。

1 0
原创粉丝点击