前置知识:
1.concurrent 并发的,一致的
2.java.util.concurrent包 java.util.concurrent包是专门为Java并发编程设计的
-----------------------------------------------------------------------------------------------------------
一:BlockingQueue接口
这个接口位于java.util.concurrent包下
看下注释:
/** * A {@link java.util.Queue} that additionally supports operations * that wait for the queue to become non-empty when retrieving an * element, and wait for space to become available in the queue when * storing an element.
翻译过来就是,
取元素的时候如果空的时候会等
存元素的时候如果满了会等。
二:BlockingQueue各个方法介绍
1.add方法(如果size不够不会阻塞,会抛出异常)
2.offer方法(如果size不够不会阻塞,会returnfalse)
3.put方法(如果size不够,会wait)
4.offer(E e, long timeout, TimeUnit unit) (如果size不够,会阻塞指定时间)
5.take(取得时候如果元素不够会wait)
6.poll(long timeout, TimeUnit unit) (如果没有元素会阻塞指定时间)
7.remainingCapacity (还有多少空隙)
8.remove(object)移除指定元素
9.contains(object)是否包含某元素
10.drainTo 整体移动
11.int drainTo(Collection<? super E> c, int maxElements); 指定移动元素的最大值
三 LinkedBlockingQueue
blockingQueue的实现类之一
看下文档的注释:
* An optionally-bounded {@linkplain BlockingQueue blocking queue} based on * linked nodes.
特点是FIFO,(first-in-first-out)
四 简单用法
由上面的第一段用法可以知道,BlockingQueue中的常用的方法是
put take drainTo()
五 示例1: put
while(true) {
try {
queue.put("");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("add item :当前size:"+queue.size());
}
上面这段代码当到第十个元素的时候,就会阻塞
六 示例2 take
take的阻塞
try {
queue.put("");
queue.put("");
queue.put("");
queue.put("");
queue.put("");
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while(true) {
try {
queue.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("take item :当前size:"+queue.size());
}
七 drainTo
drainTo方法是不阻塞线程的所以需要先用take来阻塞以下
代码如下
public class Main {
private static LinkedBlockingQueue queue = new LinkedBlockingQueue<>(10);
public static void main(String args[]) {
try {
queue.put("1");
queue.put("2");
queue.put("3");
queue.put("4");
queue.put("5");
queue.put("6");
queue.put("7");
queue.put("8");
queue.put("9");
queue.put("10");
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ArrayList<String> datas = new ArrayList<>();
while(true) {
try {
datas.add((queue.take().toString()));
queue.drainTo(datas, 2);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("take item :当前size:"+queue.size()+"当前array内容"+datas.toString());
}
}
}
打印结果:
take item :当前size:7当前array内容[1, 2, 3]
take item :当前size:4当前array内容[1, 2, 3, 4, 5, 6]
take item :当前size:1当前array内容[1, 2, 3, 4, 5, 6, 7, 8, 9]
take item :当前size:0当前array内容[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]