学习异步开发-简单实现缓冲区代码

来源:互联网 发布:红蚂蚁网络与阿里巴巴 编辑:程序博客网 时间:2024/05/29 19:56
import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;public class BoundBuffer {final Lock lock = new ReentrantLock();final Condition notFull = lock.newCondition();final Condition notEmpty = lock.newCondition();int p = -1;final Object[] items = new Object[100];public void put(Object o) throws InterruptedException {//获得锁lock.lock();try {while (p == items.length - 1) {//数据满了阻塞notFull.await();}items[++p] = o;//加入数据notEmpty.notify();//唤醒take} finally {lock.unlock();//释放锁}}public Object take() throws InterruptedException {lock.lock();try {while (p == -1) {notEmpty.await();}return items[p--];} finally {lock.unlock();}}}

0 0