一.ArrayBlockingQueue
- 简介:
成员变量:
final Object[]items;
int putIndex;//下一个被放入的元素的位置
int takeIndex;//下一个去除元素的位置
int count;
final reentrantLock lock;
private Condition notEmpty;
private Condition notFull;-
add,offer,put为插入方法,add当队列满时,抛出IllegalStateException.
Offer当队列满时立即返回false。Put当队列满时,会进入等待,只要不被中断,就会插入数据到队列中。会阻塞,响应中断。不能插入空对象,每次插入时都会执行判断,如对象为空,则抛出空指针异常。
3)主要方法:
Private void enqueuer(E x){
Final Object[]items=items;
Items[putIndex]=x;
If(++putIndex==items.length)//
putIndex=0;
count++;
notEmpty.signal();//每次插入后,都会执行notEmpty.signal,将会唤醒take线程队列中的第一个线程。
}
Private void dequeue(){
Final Object[]items=items;
E x=items[takeIndex];
Items[takeIndex]=null;
If(++takeIndex==item.length)//插入和删除都是从按顺序插入删除,当下标到最后一位时,从头开始插入删除(相当于循环)。
takeIndex==0;
notFull.signal();
}
Add():调用offer,将元素插入到队列。如果队列满则抛出IllegalStateException
Offer():不支持中断,队列满时立即返回false。
Put():当队列满时,阻塞,支持中断
Public void put(E e)throws InterruptedException{
checkNotNull(e);
final ReentrantLock lock=this.lock;
lock.IockInterruptibly();
try{
while(count==items.length)//当队列满的时候,该线程进入阻塞状态。
notFull.await();
enqueuer(e)
}
}
Take():当队列为空时,阻塞,响应中断
Public E take() throws InterruptedException{
Final ReentractLock lock=this.lock;
lock.IockInterruptibly();
try{
while(count==0)
notEmpty.await();
return dequeue();
}finally{
Lock.unlock();
}
}