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

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();
      
      
     }
   } 
 }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值