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



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();
		}
		
	}
	
	
	
	
}

你可能感兴趣的:(java)