import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 阻塞队列
* @author ETHAN
*
*/
public 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();
}
}
}
java 之 阻塞队列实现
最新推荐文章于 2023-11-29 12:27:03 发布