package Thread;
import java.util.concurrent.locks.*;
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();
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();
}
}
}
public class ConditionDemo {
}
只有代码和注释