- import java.util.concurrent.locks.Condition;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- 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 {
-
- 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();
- }
- }
复制代码
这是视频中生产者和消费者的问题,这段代码打印我复制后用Eclipse运行的结果是每生产100只后再消费100只;
可是如果是这样的话,不是应该改成while (count == items.length)
{notEmpty.signal();
notFull.await();}
和
while(count==0)
{notFull.signal();
notEmpty.await();}吗??我这样改后运行了一下,结果是一样的。但是上面那样写我想不太明白。求解答。
|
|