BlockingQueue,阻塞队列,是java.util.concurrent包下的接口,它集成了Queue类。它的实现类有ArrayBlockingQueue,ListBlockingQueue等。
注意:ArrayBlockingQueue中使用了lock和condition来控制队列的进出,因此ArrayBlockingQueue是线程安全的。
final ReentrantLock lock;
/** Condition for waiting takes */
private final Condition notEmpty;
/** Condition for waiting puts */
private final Condition notFull;
一、接口中的方法
- | Throws Exception | Special Value | Blocks | Times Out |
---|---|---|---|---|
Insert | add(o) | offer(o) | put(o) | offer(o, timeout, timeunit) |
Remove | remove(o) | poll() | take() | poll(timeout, timeunit) |
Examine | element() | peek() | not applicable | not applicable |
二、接口的实现类
1. ArrayBlockingQueue
2. DelayQueue
3. LinkedBlockingQueue
4. PriorityBlockingQueue
5. SynchronousQueue
三、应用场景
典型的应用场景莫过于,生产者和消费者模型了,生产者向队列中插入,消费者,去队列中取。
负责生产的线程不断的制造新对象并插入到阻塞队列中,直到达到这个队列的上限值。队列达到上限值之后生产线程将会被阻塞,直到消费的线程对这个队列进行消费。同理,负责消费的线程不断的从队列中消费对象,直到这个队列为空,当队列为空时,消费线程将会被阻塞,除非队列中有新的对象被插入。
四、案例
这是一个生产者,两个消费者的模型。队列没有满的情况下,生产者一直向队列中插入;队列不为空的情况下,消费者一直从队列中取。
package com.nowcoder.wenda;
import java.util.ArrayList;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
/**
* Created by wuyunlong on 17-12-2.
*/
//消费者线程
class consumer implements Runnable{
private BlockingQueue<String > q;
public consumer(BlockingQueue<String> q){
this.q = q;
}
@Override
public void run() {
try {
while (true){
System.out.println(Thread.currentThread().getName()+":"+q.take());
}
}catch (Exception e){
e.getMessage();
}
}
}
//生产者线程
class producer implements Runnable{
private BlockingQueue<String > q;
public producer(BlockingQueue<String> q){
this.q = q;
}
@Override
public void run() {
try {
for (int i=0;i<100;i++){
Thread.sleep(100);
q.put(String.valueOf(i));
}
}catch (Exception e){
e.getMessage();
}
}
}
public class MultiThread {
public static void testBlockingQueue(){
BlockingQueue<String> q = new ArrayBlockingQueue<String>(10);
new Thread(new producer(q)).start();
new Thread(new consumer(q),"consumer1").start();
new Thread(new consumer(q),"consumer2").start();
new Thread(new consumer(q),"consumer3").start();
}
public static void main(String[] args){
ArrayList<String> list =new ArrayList<>();
testBlockingQueue();
}
}