阻塞队列
阻塞队列不同于普通的对列,当队列为空的时候,take元素就会一直阻塞住,当队列满的时候,put也会阻塞住。下面为进队和出队的源码:
public class BlockingQueue { private List queue = new LinkedList(); private int limit = 10; public BlockingQueue(int limit){ this.limit = limit; } public synchronized void enqueue(Object item) throws InterruptedException { while(this.queue.size() == this.limit) { wait(); //进队的时候,如果已经队满则阻塞 } if(this.queue.size() == 0) { notifyAll(); } this.queue.add(item); } public synchronized Object dequeue() throws InterruptedException{ while(this.queue.size() == 0){ wait(); //出队的时候,如果队空,则阻塞 } if(this.queue.size() == this.limit){ notifyAll(); } return this.queue.remove(0); }}