BlockingQueue队列是一种数据结构,它有两个基本操做:在队列尾部加人一个元素,和从队列头部移除一个元素就是说,队列以一种先进先出的方式管理数据,若是你试图向一个已经满了的阻塞队列中添加一个元素或者是从一个空的阻塞队列中移除一个元素,将致使线程阻塞。java
在多线程进行合做时,阻塞队列是颇有用的工具。工做者线程能够按期地把中间结果存到阻塞队列中而其余工做者线程把中间结果取出并在未来修改它们。队列会自动平衡负载。若是第一个线程集运行得比第二个慢,则第二个线程集在等待结果时就会阻塞。若是第一个线程集运行得快,那么它将等待第二个线程集遇上来。node
而BlockingQueue队列也是一组数据集合,它继承了Queue接口,而Queue接口继承了Collection接口。数组
阻塞队列提供了四种处理方法:缓存
方法,处理方式 | 抛出异常 | 返回特殊值 | 一直阻塞 | 超时退出 |
---|---|---|---|---|
插入方法 | add(e) | offer(e) | put(e) | offer(e,time,unit) |
移除方法 | remove() | poll() | take() | poll(time,unit) |
检查方法 | element() | peek() | 不可用 | 不可用 |
java.util.concurrent包中提供了一系列的阻塞队列,好比:数据结构
ArrayBlockingQueue是一个用数组实现的有界阻塞队列。此队列按照先进先出(FIFO)的原则对元素进行排序。默认状况下不保证访问队列的公平性(不保证生产线程先阻塞先插入或者消费线程的先阻塞先获取)。而若是保证访问队列的公平性则会下降队列访问的吞吐量。多线程
咱们可使用如下代码建立一个公平的阻塞队列:工具
ArrayBlockingQueue fairQueue = new ArrayBlockingQueue(1000,true);
访问者的公平性是使用可重入锁实现的ui
public ArrayBlockingQueue(int capacity, boolean fair) { if (capacity <= 0) throw new IllegalArgumentException(); this.items = new Object[capacity]; lock = new ReentrantLock(fair); notEmpty = lock.newCondition(); notFull = lock.newCondition(); }
LinkedBlockingQueue是一个用链表实现的有界阻塞队列。此队列的默认和最大长度为Integer.MAX_VALUE。此队列按照先进先出的原则对元素进行排序。this
PriorityBlockingQueue是一个支持优先级的无界队列。默认状况下元素采起天然顺序排列,也能够经过比较器comparator来指定元素的排序规则。元素按照升序排列。.net
DelayQueue是一个支持延时获取元素的无界阻塞队列。队列使用PriorityQueue来实现。队列中的元素必须实现Delayed接口,在建立元素时能够指定多久才能从队列中获取当前元素。只有在延迟期满时才能从队列中提取元素。
咱们能够将DelayQueue运用在如下应用场景:
查看ScheduledThreadPoolExecutor里ScheduledFutureTask类。这个类实现了Delayed接口。
ScheduledFutureTask(Runnable r, V result, long ns, long period) { super(r, result); this.time = ns; this.period = period; this.sequenceNumber = sequencer.getAndIncrement(); } //延时时间最长的放置到队列的末尾 public int compareTo(Delayed other) { if (other == this) // compare zero if same object return 0; if (other instanceof ScheduledFutureTask) { ScheduledFutureTask<?> x = (ScheduledFutureTask<?>)other; long diff = time - x.time; if (diff < 0) return -1; else if (diff > 0) return 1; else if (sequenceNumber < x.sequenceNumber) return -1; else return 1; } long diff = getDelay(NANOSECONDS) - other.getDelay(NANOSECONDS); return (diff < 0) ? -1 : (diff > 0) ? 1 : 0; } //能够获取当前元素还须要延迟多久 //而当time小于当前时间时,getDelay会返回负数 public long getDelay(TimeUnit unit) { return unit.convert(time - now(), NANOSECONDS); }
延时队列的实现
public RunnableScheduledFuture<?> take() throws InterruptedException { final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { for (;;) { RunnableScheduledFuture<?> first = queue[0]; if (first == null) available.await(); else { long delay = first.getDelay(NANOSECONDS);//获取延时时间 if (delay <= 0) return finishPoll(first); first = null; // don't retain ref while waiting if (leader != null) available.await(); else { Thread thisThread = Thread.currentThread(); leader = thisThread; try { available.awaitNanos(delay); } finally { if (leader == thisThread) leader = null; } } } } } finally { if (leader == null && queue[0] != null) available.signal(); lock.unlock(); } }
SynchronousQueue是一个不存储元素的阻塞队列。每个put操做必须等待一个take操做,不然不能继续添加元素。SynchronousQueue能够当作是一个传球手,负责把生产者线程处理的数据直接传递给消费者线程。队列自己并不存储任何元素,很是适合于传递性场景,好比在一个线程中使用的数据,传递给另一个线程使用,SynchronousQueue的吞吐量高于LinkedBlockingQueue 和 ArrayBlockingQueue。
LinkedTransferQueue是一个由链表结构组成的无界阻塞TransferQueue队列。相对于其余阻塞队列LinkedTransferQueue多了tryTransfer和transfer方法。
transfer方法。若是当前有消费者正在等待接收元素(消费者使用take()方法或带时间限制的poll()方法时),transfer方法能够把生产者传入的元素马上transfer(传输)给消费者。若是没有消费者在等待接收元素,transfer方法会将元素存放在队列的tail节点,并等到该元素被消费者消费了才返回。
transfer方法的关键代码以下:
//试图把存放当前元素的s节点做为tail节点 Node pred = tryAppend(s, haveData); //让CPU自旋等待消费者消费元素。由于自旋会消耗CPU,因此自旋必定的次数后使用Thread.yield()方法来暂停当前正在执行的线程,并执行其余线程。 return awaitMatch(s, pred, e, (how == TIMED), nanos);
tryTransfer方法。则是用来试探下生产者传入的元素是否能直接传给消费者。若是没有消费者等待接收元素,则返回false。
tryTransfer方法和transfer方法的区别? tryTransfer方法不管消费者是否接收,方法当即返回。而transfer方法是必须等到消费者消费了才返回。
tryTransfer(E e, long timeout, TimeUnit unit)方法,则是试图把生产者传入的元素直接传给消费者,可是若是没有消费者消费该元素则等待指定的时间再返回,若是超时还没消费元素,则返回false,若是在超时时间内消费了元素,则返回true。
LinkedBlockingDeque是一个由链表结构组成的双向阻塞队列。所谓双向队列指的你能够从队列的两端插入和移出元素。双端队列由于多了一个操做队列的入口,在多线程同时入队时,也就减小了一半的竞争。相比其余的阻塞队列,LinkedBlockingDeque多了addFirst,addLast,offerFirst,offerLast,peekFirst,peekLast等方法,以First单词结尾的方法,表示插入,获取(peek)或移除双端队列的第一个元素。以Last单词结尾的方法,表示插入,获取或移除双端队列的最后一个元素。另外插入方法add等同于addLast,移除方法remove等效于removeFirst。可是take方法却等同于takeFirst,因此咱们在使用时仍是用带有First和Last后缀的方法更清楚。在初始化LinkedBlockingDeque时能够初始化队列的容量,用来防止其再扩容时过渡膨胀。另外双向阻塞队列能够运用在“工做窃取”模式中。
若是队列是空的,消费者会一直等待,当生产者添加元素时候,消费者是如何知道当前队列有元素的呢?若是让你来设计阻塞队列你会如何设计,让生产者和消费者可以高效率的进行通信呢?让咱们先来看看JDK是如何实现的。
使用通知模式实现。所谓通知模式,就是当生产者往满的队列里添加元素时会阻塞住生产者,当消费者消费了一个队列中的元素后,会通知生产者当前队列可用。经过查看JDK源码发现ArrayBlockingQueue使用了Condition来实现,代码以下:
private final Condition notFull; private final Condition notEmpty; public ArrayBlockingQueue(int capacity, boolean fair) { ...... notEmpty = lock.newCondition(); notFull = lock.newCondition(); } public void put(E e) throws InterruptedException { checkNotNull(e); final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { while (count == items.length) notFull.await(); enqueue(e); } finally { lock.unlock(); } } public E take() throws InterruptedException { final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { while (count == 0) notEmpty.await(); return dequeue(); } finally { lock.unlock(); } } //插入元素 private void enqueue(E x) { final Object[] items = this.items; items[putIndex] = x; if (++putIndex == items.length) putIndex = 0; count++; notEmpty.signal(); }
当咱们往队列里插入一个元素时,若是队列不可用,阻塞生产者主要经过LockSupport.park(this);来实现
public final void await() throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); Node node = addConditionWaiter(); int savedState = fullyRelease(node); int interruptMode = 0; while (!isOnSyncQueue(node)) { LockSupport.park(this);//经过LockSupport.park挂起当前线程 if ((interruptMode = checkInterruptWhileWaiting(node)) != 0) break; } if (acquireQueued(node, savedState) && interruptMode != THROW_IE) interruptMode = REINTERRUPT; if (node.nextWaiter != null) // clean up if cancelled unlinkCancelledWaiters(); if (interruptMode != 0) reportInterruptAfterWait(interruptMode); }
关于LockSupport的park和unpark方法咱们能够参考https://my.oschina.net/cqqcqqok/blog/2049659
参考地址: http://ifeve.com/java-blocking-queue/