Lock+Condition 模仿 阻塞队列(BlockQueue)

 

 

package multithreading;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * synchronized 的wait notify 没有条件判断
 * Lock 的Condition的await,signal有条件判断.
 * 也就是在一个Lock上可以有多个Condition
 *
 */

public class MyBlockingQueue {

	private final Lock lock=new ReentrantLock();
	private final Condition noEmpty=lock.newCondition();
	private final Condition noFull=lock.newCondition();
	
	private final Object[] items=new Object[100];
	private int putIndex,getIndex,count;
	
	public Object get() throws InterruptedException{
		
		lock.lock();
		try {
			while(count==0)//队列空了
				noEmpty.await();//消费者线程等待
			count--;//计数--
			
			Object resultVal=items[getIndex++];//消费,指针向后移动;
			if(getIndex==items.length)//超出队列范围了
				getIndex=0;//归零
			
			noFull.signal();//通知生产者
			return resultVal;
		}finally{
			lock.unlock();	
		}

	}
	
	public void put(Object o) throws InterruptedException {
		
		lock.lock();
		try {
			while(count==items.length)//队列满了
				noFull.await();//生产者线程等待
			count++;//计数++
			
			items[putIndex++]=o;//放进去,指针向后移
			if(putIndex==items.length)//超出队列范围了
				putIndex=0;//归零
			
			noEmpty.signal();//通知消费者
			
		}finally{
			lock.unlock();
		}
	}

}


 

你可能感兴趣的:(Lock+Condition 模仿 阻塞队列(BlockQueue))