Java并发:阻塞队列BlockingQueue实现原理分析,linux内核技术手册pdf

  1. BlockingQueue通常用来作为生产者-消费者的队列的,但是它也支持Collection接口提供的方法,比如使用remove(x)来删除一个元素,但是这类操作并不是很高效,因此尽量在少数情况下使用,如:当一条入队的消息需要被取消的时候。

  2. BlockingQueue的实现都是线程安全的,所有队列的操作或使用内置锁或是其他形式的并发控制来保证原子。但是一些批量操作如:addAll,containsAll, retainAll和removeAll不一定是原子的。如 addAll© 有可能在添加了一些元素后中途抛出异常,此时 BlockingQueue 中已经添加了部分元素。

  3. BlockingQueue不支持类似close或shutdown等关闭操作。

下面这一段是并发大师 DougLea 写的一段demo,使用BlockingQueue 来保证多生产者和消费者时的线程安全

// Doug Lea: BlockingQueue 可以用来保证多生产者和消费者时的线程安全

class Producer implements Runnable{

private final BlockingQueue queue;

Producer(BlockingQueue q){

queue = q;

}

public void run(){

try{

while(true) {

queue.put(produce()); // 阻塞式插入

}

}catch(InterruptedException ex){ …handle… }

}

Object produce() { … }

}

class Consumer implements Runnable{

private final BlockingQueue queue;

Consumer(BlockingQueue q){

queue = q;

}

public void run(){

try{

while(true) {

consume(queue.take())); // 阻塞式获取

}

}catch(InterruptedException ex){ …handle… }

}

void consume(Object x) { … }

}

class Setup{

void main(){

BlockingQueue q = new SomeQueueImplementation();

Producer p = new Producer(q);

Consumer c1 = new Consumer(q);

Consumer c2 = new Consumer(q);

new Thread§.start();

new Thread(c1).start();

new Thread(c2).start();

}

}

阻塞队列提供的方法

=============

BlockingQueue 对插入操作、移除操作、获取元素操作提供了四种不同的方法用于不同的场景中使用:

方法类别抛出异常返回特殊值一直阻塞超时退出插入add(e)offer(e)put(e)offer(e, time, unit)移除remove()poll()take()poll(time, unit)瞅一瞅element()peek()

博主在这边大概解释一下,如果队列可用时,上面的几种方法其实效果都差不多,但是当队列空或满时,会表现出部分差异:

  1. 抛出异常&#

你可能感兴趣的:(程序员,面试,java,后端)