BlockingQueue之---ArrayBlockingQueue

1、直接上代码,注释已经很详细:

  自己拿走试验就行

/**
* ArrayBlockingQueue:以数组形式保存数据的阻塞式的有界队列
* 1、不可扩容--有界
*/
public class Q_ArrayBlockingQueue {

//容量为5的队列,不可扩容,最多只能装5个
private static BlockingQueue<String> strQueue = new ArrayBlockingQueue<String>(5);

public static void main(String[] args) {

//先把队列填满,测试其方法
for (int i = 0; i < 5; i++) {
//add():添加,有返回值:boolean类型
strQueue.add("str: " + i);
}

//1:add()方法:有boolean类型返回值,添加成功true;失败:报错。
// boolean addResult = strQueue.add("str:add");
// System.out.println(addResult);

//2:offer():boolean类型返回值,成功true;失败false
// boolean offerResult = strQueue.offer("str: offer");
//2.1:还可以增加等待时间,超时报错
// boolean offerResult = false;
// try {
// offerResult = strQueue.offer("str: offer", 2, TimeUnit.SECONDS);
// } catch (InterruptedException e) {
// System.out.println(e.fillInStackTrace());
// }

// //3:put():阻塞方法,如果没有位置了,阻塞等到有位置位置,与take()天生一对
// try {
// strQueue.put("str: put");
// } catch (InterruptedException e) {
// System.out.println(e.fillInStackTrace());
// }

//4:take()方法:目标是第一个元素,阻塞到拿到为止,必须得拿到,性格强势
// try {
// String takeResult = strQueue.take();
// System.out.println(takeResult);
// } catch (InterruptedException e) {
// System.out.println(e.fillInStackTrace());
// }

//5:poll()比take()温柔多了,等你一段时间,拿不到的话就是null,不等了
String pollResult = strQueue.poll();
System.out.println(pollResult);

}

}