疯狂

STANDING ON THE SHOULDERS OF GIANTS
posts - 481, comments - 486, trackbacks - 0, articles - 1
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

Condition

Posted on 2011-10-17 17:28 疯狂 阅读(658) 评论(0)  编辑  收藏 所属分类: concurrent

Condition(条件)Object 监视器方法(waitnotifynotifyAll)分解成截然不同的对象,以便通过将这些对象与任意 Lock 实现组合使用,为每个对象提供多个等待 set (wait-set)。其中,Lock 替代了 synchronized 方法和语句的使用,Condition 替代了 Object 监视器方法的使用。
下面解释下Condition api里面的例子(生产者,消费者):

public class ConditionTest {

 final Lock lock = new ReentrantLock();
     final Condition notFull  = lock.newCondition(); //生产者的前提条件,没有达到次条件就阻塞
     final Condition notEmpty = lock.newCondition(); //消费者的前提条件,没有达到次条件就阻塞
  
     final Object[] items = new Object[100];
     int putptr, takeptr, count;
  //生产
     public void put(Object x) throws InterruptedException {
       lock.lock();
       try {
         while (count == items.length)//如果满了,就让需要条件为:没满的的线程(生产者)等
           notFull.await();
         items[putptr] = x;
         if (++putptr == items.length) putptr = 0;
         ++count;
         notEmpty.signal();//如果已经生产了,就让需要条件为不为空的线程(消费者)执行
       } finally {
         lock.unlock();
       }
     }
  //消费
     public Object take() throws InterruptedException {
       lock.lock();
       try {
         while (count == 0)//如果为空就让需要条件为不为空的线程(消费者)等
           notEmpty.await();
         Object x = items[takeptr];
         if (++takeptr == items.length) takeptr = 0;
         --count;
         notFull.signal();//如果消费了,就让条件为不满的线程(生产者)执行
         return x;
       } finally {
         lock.unlock();
       }
     }
   }

 


只有注册用户登录后才能发表评论。


网站导航: