阻塞队列与普通队列的区别在于,当队列是空的时,从队列中获取元素的操作将会被阻塞,或者当队列是满时,往队列里添加元素的操作会被阻塞。试图从空的阻塞队列中获取元素的线程将会被阻塞,直到其他的线程往空的队列插入新的元素。同样,试图往已满的阻塞队列中添加新元素的线程同样也会被阻塞,直到其他的线程使队列重新变得空闲起来,如从队列中移除一个或者多个元素,或者完全清空队列,下图展示了如何通过阻塞队列来合作:
线程1往阻塞队列中添加元素,而线程2从阻塞队列中移除元素
从5.0开始,JDK在java.util.concurrent包里提供了阻塞队列的官方实现。尽管JDK中已经包含了阻塞队列的官方实现,但是熟悉其背后的原理还是很有帮助的。
1.利用wait,notify();
package com.thread.ticket;
import java.util.LinkedList;
import java.util.List;
public class MyBlockingQueue {
private List queue = new LinkedList();
private int limit;
public MyBlockingQueue( int limit) {
this.limit = limit;
}
public synchronized void put(Object o) throws InterruptedException {
if(queue.size()==limit){
wait();
}
if(this.queue.size()==0){
notifyAll();
}
this.queue.add(o);
}
public synchronized Object get() throws InterruptedException {
if(this.queue.size() == 0){
wait();
}
if(this.queue.size() == this.limit){
notifyAll();
}
return queue.remove(0);
}
}
必须注意到,在enqueue和dequeue方法内部,只有队列的大小等于上限(limit)或者下限(0)时,才调用notifyAll方法。如果队列的大小既不等于上限,也不等于下限,任何线程调用enqueue或者dequeue方法时,都不会阻塞,都能够正常的往队列中添加或者移除元素。
http://tutorials.jenkov.com/java-concurrency/blocking-queues.html
2.利用lock,Condition,await,signal
package com.thread.ticket;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class BoundedBuffer {
Lock lock = new ReentrantLock();
final Condition notFull = lock.newCondition();
final Condition notEmpty = lock.newCondition();
final Object items[] = new Object[100];
int puter,outer,count;
public void put(Object o) throws InterruptedException{
try{
lock.lock();
if(items.length == count){
notFull.await();
}
items[puter] = o;
if(++puter == items.length) puter = 0;
++count;
notEmpty.signal();
}finally{
lock.unlock();
}
}
public void take() throws InterruptedException{
try{
lock.lock();
if(items.length == 0){
notEmpty.await();
}
Object x= items[outer];
if(++outer == items.length) outer = 0;
--count;
notFull.signal();
}finally{
lock.unlock();
}
}
}