java.util.concurrent.BlockingQueue接口是Queue接口的子接口,并且还支持诸如在检索元素之前等待队列变为非空的操作,并等待队列中的空间可用之前存储元素.
BlockingQueue方法
Sr.No. | 方法&说明 |
---|---|
1 | boolean add(E e) 如果可以在不违反容量限制的情况下立即执行此操作,则将指定的元素插入此队列,成功时返回true并抛出IllegalStateException目前没有空位. |
2 | boolean contains(Object o) 如果此队列包含指定的元素,则返回true. |
3 | int drainTo(Collection<?super E> c) 从此队列中删除所有可用元素并将它们添加到给定集合中. |
4 | int drainTo(Collection<?super E> c,int maxElements) 从此队列中删除最多给定数量的可用元素并将它们添加到给定的coll中. |
5 | boolean offer(E e) 如果可以在不违反容量限制的情况下立即执行此操作,则将指定的元素插入此队列,成功时返回true,如果当前没有空格则返回false. |
6 | boolean offer(E e, long timeout, TimeUnit unit) 插入指定的元素进入此队列,如果需要空间可用,则等待指定的等待时间. |
7 | E poll(long timeout, TimeUnit unit) 检索并删除此队列的头部,如果需要,等待指定的等待时间以使元素成为可用. |
8 | void put(E e) 将指定的元素插入此队列,等待空间变为可用. |
9 | int remainingCapacity() 返回理想情况下(在没有内存或资源限制的情况下)此队列可以无阻塞地接受的其他元素的数量,或者整数.MAX_VALUE,如果没有内在限制. |
10 | boolean remove(Object o) 从此队列中删除指定元素的单个实例,如果它存在. |
11 | E take( ) 检索并移除此队列的头部,必要时等待元素可用. |
示例
以下TestThread程序显示了基于线程的环境中BlockingQueue接口的使用情况.
import java.util.Random;import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;public class TestThread { public static void main(final String[] arguments) throws InterruptedException { BlockingQueuequeue = new ArrayBlockingQueue (10); Producer producer = new Producer(queue); Consumer consumer = new Consumer(queue); new Thread(producer).start(); new Thread(consumer).start(); Thread.sleep(4000); } static class Producer implements Runnable { private BlockingQueue queue; public Producer(BlockingQueue queue) { this.queue = queue; } @Override public void run() { Random random = new Random(); try { int result = random.nextInt(100); Thread.sleep(1000); queue.put(result); System.out.println("Added: " + result); result = random.nextInt(100); Thread.sleep(1000); queue.put(result); System.out.println("Added: " + result); result = random.nextInt(100); Thread.sleep(1000); queue.put(result); System.out.println("Added: " + result); } catch (InterruptedException e) { e.printStackTrace(); } } } static class Consumer implements Runnable { private BlockingQueue queue; public Consumer(BlockingQueue queue) { this.queue = queue; } @Override public void run() { try { System.out.println("Removed: " + queue.take()); System.out.println("Removed: " + queue.take()); System.out.println("Removed: " + queue.take()); } catch (InterruptedException e) { e.printStackTrace(); } } }}
这将产生以下结果.
输出
Added: 52Removed: 52Added: 70Removed: 70Added: 27Removed: 27