1.BlockingQueue接口:
public interface BlockingQueue<E>
extends
Queue<E>
抛出异常 特殊值 阻塞 超时
插入 add(e) offer(e) put(e) offer(e, time, unit)
移除 remove() poll() take() poll(time, unit)
检查 element() peek() 不可用 不可用
2.ArrayBlockingQueue
接口 BlockingQueue<E>
类型参数:
E - 在此 collection 中保持的元素类型
所有超级接口:
Collection<E>, Iterable<E>, Queue<E>
所有已知子接口:
BlockingDeque<E>
所有已知实现类:
ArrayBlockingQueue, DelayQueue, LinkedBlockingDeque, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue
一个由数组支持的有界阻塞队列。此队列按 FIFO(先进先出)原则对元素进行排序。队列的头部 是在队列中存在时间最长的元素。队列的尾部 是在队列中存在时间最短的元素。新元素插入到队列的尾部,队列获取操作则是从队列头部开始获得元素。
这是一个典型的“有界缓存区”,固定大小的数组在其中保持生产者插入的元素和使用者提取的元素。一旦创建了这样的缓存区,就不能再增加其容量。试图向已满队列中放入元素会导致操作受阻塞;试图从空队列中提取元素将导致类似阻塞。
此类支持对等待的生产者线程和使用者线程进行排序的可选公平策略。默认情况下,不保证是这种排序。然而,通过将公平性 (fairness) 设置为 true 而构造的队列允许按照 FIFO 顺序访问线程。公平性通常会降低吞吐量,但也减少了可变性和避免了“不平衡性”。
eg:
package com.qunar.thread;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
public class ArrayBlockingQueue {
public static void main(String[] args) {
final BlockingQueue<Integer> queue = new java.util.concurrent.ArrayBlockingQueue<Integer>(3);
for(int i =0;i<2;i++){
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep((long) Math.random() * 10000);
System.out.println(Thread.currentThread().getName()
+ "准备放数据");
int data = new Random().nextInt();
queue.put(data);
System.out.println(Thread.currentThread().getName()
+ "已經放入數據:" + data);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
new Thread(new Runnable() {
@Override
public void run() {
while(true){
try {
Thread.sleep(10000);
System.out.println(Thread.currentThread().getName()
+ "准备取数据");
int data = queue.take();
System.out.println(Thread.currentThread().getName()
+ "取得数据:" + data+",目前隊列中有"+queue.size()+"個數據");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}