ArrayBlockingQueue:
一个由数组支持的有界阻塞队列。此队列按 FIFO(先进先出)原则对元素进行排序。队列的头部 是在队列中存在时间最长的元素。队列的尾部 是在队列中存在时间最短的元素。新元素插入到队列的尾部,队列检索操作则是从队列头部开始获得元素。
ArrayBlockingQueue的常用方法:
put:将指定的元素添加到此队列的尾部,如果必要,将等待可用的空间。
take:检索并移除此队列的头部,如果此队列不存在任何元素,则一直等待。
offer:将指定的元素插入到此队列的尾部(如果可能),如果此队列已满,则立即返回。
poll:检索并移除此队列的头,如果此队列为空,则返回null。
说明:put、offer都是向队列中添加元素,take、poll都是从队列中移除元素。put和take对应一组,是阻塞式的;offer、poll对应一组,是非阻塞式的。
实例:
package com.bijian.thread; import java.util.concurrent.BlockingQueue; public class Producer implements Runnable { private String name = null; private BlockingQueue<String> queue = null; public Producer(String name, BlockingQueue<String> queue) { this.name = name; this.queue = queue; } @Override public void run() { try { for (int i = 0; i < 10; i++) { queue.put(name + ": " + i); System.out.println("Product:" + name + ": " + i); Thread.sleep((long) (Math.random() * 1000)); } } catch (Exception e) { e.printStackTrace(); } } }
package com.bijian.thread; import java.util.concurrent.BlockingQueue; public class Consumer implements Runnable { private String name; private BlockingQueue<String> queue = null; public Consumer(String name, BlockingQueue<String> queue) { this.name = name; this.queue = queue; } @Override public void run() { try { for (int i = 0; i < 5; i++) { String prod = queue.take(); System.out.println("Consumer:" + name + ": " + prod); Thread.sleep((long) (Math.random() * 1000)); } } catch (Exception e) { e.printStackTrace(); } } }
package com.bijian.thread; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Main { public static void main(String[] args) { BlockingQueue<String> queue = new ArrayBlockingQueue<String> (3); ExecutorService service = Executors.newCachedThreadPool(); Producer producer = new Producer("P1", queue); Consumer consumer = new Consumer("C1", queue); Consumer consumer1 = new Consumer("C2", queue); service.execute(producer); service.execute(consumer); service.execute(consumer1); service.shutdown(); } }
运行结果:
Product:P1: 0 Consumer:C1: P1: 0 Product:P1: 1 Consumer:C2: P1: 1 Product:P1: 2 Consumer:C1: P1: 2 Product:P1: 3 Consumer:C2: P1: 3 Product:P1: 4 Consumer:C1: P1: 4 Product:P1: 5 Consumer:C2: P1: 5 Product:P1: 6 Consumer:C1: P1: 6 Product:P1: 7 Consumer:C2: P1: 7 Product:P1: 8 Product:P1: 9 Consumer:C1: P1: 8 Consumer:C2: P1: 9