BlockingQueue在生产者消费者模式中运用非常广泛,生产者往队列中增加产品,消费中从队列中获取产品。在增加和删除队列元素的时候,是否阻塞是可选的,比如队列为空时再获取队列元素时,是返回空、返回null还是抛异常,下面的摘自api文档的说明:
Throws exception | Special value | Blocks | Times out | |
Insert | add(e) | offer(e) | put(e) | offer(e, time, unit) |
Remove | remove() | poll() | take() | poll(time, unit) |
Examine | element() | peek() | not applicable | not applicable |
下面是一个生成这和消费者的例子:
final ArrayBlockingQueue<String> iphones = new ArrayBlockingQueue<String>(10);
//apple company product iphones
new Thread(new Runnable(){
@Override
public void run() {
int num = 0;
while(true){
try {
Thread.sleep(500);
iphones.put("iphone" + (++num));
System.out.println("produce a iphone,total size is " + iphones.size());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
// customers
for(int i = 0;i<3;i++){
new Thread(new Runnable(){
@Override
public void run() {
while(true){
try {
Thread.sleep(new Random().nextInt(5000));
String iphone = iphones.take();
System.out.println(Thread.currentThread().getName() + ": i get a iphone : " + iphone+",left " + iphones.size());
}catch(Exception e){
}
}
}
}).start();
}
部分执行结果:
produce a iphone,total size is 0
Thread-1: i get a iphone : iphone1,left 0
produce a iphone,total size is 1
Thread-1: i get a iphone : iphone2,left 0
produce a iphone,total size is 1
Thread-2: i get a iphone : iphone3,left 0
produce a iphone,total size is 1
Thread-3: i get a iphone : iphone4,left 0
produce a iphone,total size is 1
produce a iphone,total size is 2
produce a iphone,total size is 3
Thread-1: i get a iphone : iphone5,left 2
produce a iphone,total size is 3
produce a iphone,total size is 4
produce a iphone,total size is 5
Thread-2: i get a iphone : iphone6,left 4