介绍
一个由数组支持的有界阻塞队列。此队列按 FIFO(先进先出)原则对元素进行排序。队列的头部 是在队列中存在时间最长的元素。队列的尾部 是在队列中存在时间最短的元素。新元素插入到队列的尾部,队列获取操作则是从队列头部开始获得元素。
这是一个典型的“有界缓存区”,固定大小的数组在其中保持生产者插入的元素和使用者提取的元素。一旦创建了这样的缓存区,就不能再增加其容量。试图向已满队列中放入元素会导致操作受阻塞;试图从空队列中提取元素将导致类似阻塞。
此类支持对等待的生产者线程和使用者线程进行排序的可选公平策略。默认情况下,不保证是这种排序。然而,通过将公平性 (fairness) 设置为 true 而构造的队列允许按照 FIFO 顺序访问线程。公平性通常会降低吞吐量,但也减少了可变性和避免了“不平衡性”。
示例
package com.chen.concurrent;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.commons.lang.RandomStringUtils;
public class ArrayBlockingQueueTest {
public static void main(String[] args) {
ArrayBlockingQueueTest arrayBlockingQueueTest = new ArrayBlockingQueueTest();
//arrayBlockingQueueTest.test01();
arrayBlockingQueueTest.test02();
}
public void test01(){
ArrayBlockingQueue<String> arrayBlockingQueue = new ArrayBlockingQueue<String>(10);
arrayBlockingQueue.add("chenmin");
System.out.println(arrayBlockingQueue.remove());
System.out.println(arrayBlockingQueue.contains("chenmin"));
}
public void test02(){
ArrayBlockingQueue<String> arrayBlockingQueue = new ArrayBlockingQueue<String>(10);
ExecutorService executorService = Executors.newFixedThreadPool(5);
for(int i = 0;i < 3;i++){
Thread t_producer = new Thread(new Producer(arrayBlockingQueue),"thread_producer"+i);
t_producer.start();
}
for(int i=0;i<5;i++){
Thread t_consumer = new Thread(new Consumer(arrayBlockingQueue),"thread_consumer"+i);
t_consumer.start();
}
}
class Producer implements Runnable{
private ArrayBlockingQueue<String> arrayBlockingQueue;
public Producer(ArrayBlockingQueue<String> arrayBlockingQueue) {
this.arrayBlockingQueue = arrayBlockingQueue;
}
@Override
public void run() {
while(true){
try {
Thread.sleep(1000);
String temp = RandomStringUtils.randomAlphabetic(10);
System.out.println(Thread.currentThread().getName()+"向队列中添加一条数据:"+temp);
arrayBlockingQueue.put(temp);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable{
private ArrayBlockingQueue<String> arrayBlockingQueue;
public Consumer(ArrayBlockingQueue<String> arrayBlockingQueue) {
this.arrayBlockingQueue = arrayBlockingQueue;
}
@Override
public void run() {
while(true){
try {
Thread.sleep(5000);
String temp = arrayBlockingQueue.take();
System.out.println(Thread.currentThread().getName()+"从队列中获取一条数据:"+temp);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}