生产者消费者问题的java实现

来源:互联网 发布:时代互联 域名转出 编辑:程序博客网 时间:2024/05/19 23:14
class BoundedBuffer {
   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();
  1.      try {
       while (count == items.length) 
         notFull.await();//一旦某个进程调用了await方法,他就进入了等待该条件集
合的状态,这里调用了await(),便进入了等待Notfull这个条件的状态,并且放弃了该锁
       items[putptr] = x; 
       if (++putptr == items.length) putptr = 0;
       ++count;
       notEmpty.signal();
     } finally {
       lock.unlock();
     }
   }
Put 能够执行的条件不仅包括锁被解除,而且,他需要将阻塞状态维持到另一个进程
在同一个条件上调用singal()方法为止
 
   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();//当另一个进程发出一个信号使得NotFull条件为真时,
那么上面的notfull.await()时的阻塞状态解除
       return x;
     } finally {
       lock.unlock();
     }
   } 
 }