ETHAN IN IT

Lost in it

java 之 阻塞队列实现

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 object import class
个人分类: java Thread
上一篇java 之 读写锁 线程间互斥
下一篇java 之 Condition 线程间通信
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭