java 之 阻塞队列实现

来源:互联网 发布:2017年软考程序员答案 编辑:程序博客网 时间:2024/04/30 06:21
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();}}}