BlockingQueue
当生产者线程试图向BlockingQueue中放入元素时,如果该队列已满,则该线程被阻塞,对应put方法;
当消费者线程试图从BlockingQueue中取出元素时,如果该队列已空,则该线程被阻塞,对应take方法。
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class BlockingQueue
{
//显示定义一个可重入锁
final Lock lock = new ReentrantLock();
//获得指定lock对象的condition
final Condition notFull = lock.newCondition();
final Condition notEmpty = lock.newCondition();
//定义一个Object数组
final Object[] items = new Object[100];
//定义一些标识变量
int putptr, takeptr, count;
//向队列中放元素
public void put(Object o) throws InterruptedException
{
lock.lock();//加锁
try
{
while(count == items.length)//若队列满,则阻塞非满线程
{
notFull.await();
}
items[putptr++] = o;//否则将元素加入数组中
if(putptr == items.length)//若队列满,则将put标识清0
{
putptr = 0;
}
count++;//队列中元素的个数自增
notEmpty.signal();//唤醒非空线程
}
finally
{
lock.unlock();//释放锁
}
}
//从队列中取元素
public Object take() throws InterruptedException
{
lock.lock();//加锁
try
{
while(count == 0)//若队列空,则阻塞非空线程
{
notEmpty.await();
}
Object o = items[takeptr++];//将数组中的元素存入Object变量
if(takeptr == items.length)//若队列变空,则将take标识清0
{
takeptr = 0;
}
count--;//数组元素个数自减
notFull.signal();//唤醒非满线程
return o;//返回需要取出的元素
}finally
{
lock.unlock();//释放锁
}
}
}