【转】Java并发编程:阻塞队列

  在前面几篇文章中,我们讨论了同步容器(Hashtable、Vector),也讨论了并发容器(ConcurrentHashMap、CopyOnWriteArrayList),这些工具都为我们编写多线程程序提供了很大的方便。今天我们来讨论另外一类容器:阻塞队列。

  在前面我们接触的队列都是非阻塞队列,比如PriorityQueue、LinkedList(LinkedList是双向链表,它实现了Dequeue接口)。

  使用了非阻塞队列的时候有一个很大的问题就是:它不会对当前线程产生阻塞,那么在面对类似消费者-生产者的模型时,就必须额外地实现同步策略以及线程间唤醒策略,这个实现起来就非常麻烦。但是有了阻塞队列就不一样了,它会对当前线程产生阻塞,比如一个线程从一个空的阻塞队列中取元素,此时线程会被阻塞直到阻塞队列中有了元素。当队列中有元素后,被阻塞的线程会自动被唤醒(不需要我们编写代码去唤醒)。这样提供了极大的方便性

  

一、几种主要的阻塞队列

  自从Java 1.5之后,在java.util.concurrent包下提供了若干个阻塞队列,主要有以下几个:

  ArrayBlockingQueue:基于数组实现的一个有界阻塞队列,在创建ArrayBlockingQueue对象时必须指定容量大小。并且可以指定公平性与非公平性,默认情况下为非公平的。所谓公平的访问队列是指阻塞的线程,可以按照阻塞的先后顺序访问队列,先阻塞的线程先访问ArrayBlockingQueue队列;非公平性是对先等待的线程是非公平的,当队列可用时,阻塞的线程都可以争夺访问队列的资格,有可能先阻塞的线程最后才能够访问队里。然后为了保证公平性,通常会降低吞吐量。

  LinkedBlockingQueue:基于链表实现的一个有界阻塞队列,在创建LinkedBlockingQueue对象时如果不指定容量大小,则默认大小为Integer.MAX_VALUE。

  PriorityBlockingQueue:以上2种队列都是先进先出队列,而PriorityBlockingQueue却不是,它会按照元素的优先级对元素进行排序,按照优先级顺序出队,每次出队的元素都是优先级最高的元素。注意,此阻塞队列为无界阻塞队列,即容量没有上限(通过源码可知,其没有容器满的信号标志)。

  DelayQueue:基于PriorityQueue,一种延时阻塞队列,DelayQueue中的元素只有当其指定的延时时间到了,才能够从队列中获取到该元素。DelayQueue也是一个无界队列,因此队列中插入数据的线程(生产者)永远不会被阻塞,而只有获取数据的线程(消费者)才会被阻塞

二、阻塞队列中的方法 VS 非阻塞队列中的方法

1、非阻塞队列中的几个主要方法:

  add(E e):将元素e插入到队列末尾,如果插入成功,则返回true;如果插入失败(即队列已满),则会抛出异常;

  remove():移除队首元素,若移除成功,则返回true;如果移除失败(队列为空),则会抛出异常;

  offer(E e):将元素e插入到队列末尾,如果插入成功,则返回true;如果插入失败(即队列已满),则返回false;

  poll():移除并获取队首元素,若成功,则返回队首元素;否则返回null;

  peek():获取队首元素,若成功,则返回队首元素;否则返回null

  对于非阻塞队列,一般情况下建议使用offer、poll和peek三个方法,不建议使用add和remove方法。因为使用offer、poll和peek三个方法可以通过返回值判断操作成功与否,而使用add和remove方法却不能达到这样的效果。注意,非阻塞队列中的方法都没有进行同步措施

 

2、阻塞队列中的几个主要方法:

  阻塞队列包括了非阻塞队列中的大部分方法,上面列举的5个方法在阻塞队列中都存在,但是要注意这5个方法在阻塞队列中都进行了同步措施。除此之外,阻塞队列提供了另外4个非常有用的方法:

  put(E e):向队尾存入元素,如果队列满,则等待;

  take():从队首取元素,如果队列为空,则等待;

  offer(E e,long timeout,TimUnit unit):向队尾存入元素,如果队列满,则等待一定的时间,当时间期限达到时,如果还没有插入成功,则返回false;否则返回true;

  poll(long timeout,TimeUnit unit):从队首取元素,如果队列为空,则等待一定的时间,当时间期限达到时,如果未取到,则返回null;否则返回取得的元素;

三、阻塞队列的实现原理

  前面谈到了非阻塞队列和阻塞队列中常用的方法,下面来探讨阻塞队列的实现原理,本文以ArrayBlockingQueue为例,其它阻塞队列实现原理可能和ArrayBlockingQueue有一些差别,但是大体思路应该类似。

  首先,看一下ArrayBlockingQueue类中的几个成员变量:

 1 public class ArrayBlockingQueue<E> extends AbstractQueue<E>
 2         implements BlockingQueue<E>, java.io.Serializable {
 3 
 4     /**
 5      * Serialization ID. This class relies on default serialization
 6      * even for the items array, which is default-serialized, even if
 7      * it is empty. Otherwise it could not be declared final, which is
 8      * necessary here.
 9      */
10     private static final long serialVersionUID = -817911632652898426L;
11 
12     /** The queued items */
13     final Object[] items;
14 
15     /** items index for next take, poll, peek or remove */
16     int takeIndex;
17 
18     /** items index for next put, offer, or add */
19     int putIndex;
20 
21     /** Number of elements in the queue */
22     int count;
23 
24     /*
25      * Concurrency control uses the classic two-condition algorithm
26      * found in any textbook.
27      */
28 
29     /** Main lock guarding all access */
30     final ReentrantLock lock;
31     /** Condition for waiting takes */
32     private final Condition notEmpty;
33     /** Condition for waiting puts */
34     private final Condition notFull;

  可以看出,ArrayBlockingQueue中用来存储元素的实际上是一个数组,takeIndex和putIndex分别表示队首元素和队尾元素的下标,count表示队列中元素的个数。

  lock是一个可重入锁,notEmpty和notFull是等待条件

  下面看一下ArrayBlockingQueue的构造器,构造器有三个重载版本:

1 public ArrayBlockingQueue(int capacity) {
2 }
3 public ArrayBlockingQueue(int capacity, boolean fair) {
4  
5 }
6 public ArrayBlockingQueue(int capacity, boolean fair,
7                           Collection<? extends E> c) {
8 }

  第一个构造器只有一个参数用来指定容量,第二个构造器可以指定容量和公平性,第三个构造器可以指定容量、公平性以及用另外一个集合的数据对队列进行初始化。

  然后看它的两个关键方法的实现:put()和take():

  下面是put()方法实现:

 1 public void put(E e) throws InterruptedException {
 2     if(e == null) throws new NullPointerException();
 3 
 4     final ReentrantLock lock = this.lock();
 5     // 允许在等待时由其它线程调用等待线程的Thread.interrupt方法来中断等待线程的等待,当等待线程被打断时,
 6     // 会被要求处理InterruptedException,或将InterruptedException抛出
 7     lock.lockInterruptibly();
 8     try {
 9         try {
10             while(count == items.length)
11                 notFull.await();
12         }catch(InterruptedException ie) {
13             notFull.signal();   // propagate to non-interrupted thread
14             throw ie;
15         }
16 
17         insert(e);
18     } finally {
19         lock.unlock();
20     }
21 }

  从put方法的实现可以看出,它先获取了锁,并且获取的锁是可中断锁,然后判断当前元素个数是否等于数组的长度,如果相等,则调用notFull.await()进行等待,如果捕获到中断异常,则唤醒线程并抛出异常

  当队列未满或被其它线程唤醒时,通过insert(e)方法插入元素,最后解锁。

  我们看一下insert方法的实现:

1 private insert(E x) {
2     items[putIndex] = x;
3     putIndex = inc(putIndex);
4     ++count;
5     notEmpty.signal();
6 }

  它是一个private方法,插入成功后,通过notEmpty唤醒正在等待取元素的线程。

  下面是take()方法的实现:

 1 public E take() throws InterruptedException {
 2     final ReentrantLock lock = this.lock;
 3 
 4     lock.lockInterruptibly();
 5     try {
 6         try {
 7             while(count == 0)
 8                 notEmpty.await();
 9         }catch(InterruptedException) {
10             notEmpty.signal();  // propagate to non-interrupted thread
11             throw ie;
12         }
13 
14         E x = extract();
15         return x;
16     }finally {
17         lock.unlock();
18         
19     }
20 }

  跟put方法实现很类似,只不过put方法等待的是notFull信号,而take方法等待的是notEmpty信号。在take方法中,如果可以取元素,则通过extract方法取得元素,下面是extract方法的实现:

1 private E extract() {
2     final E[] items = this.items;
3     E x = items[takeIndex];
4     items[takeIndex] = null;
5     takeIndex = inc(takeIndex);
6     --count;
7     notFull.signal();
8     return x;
9 }

  跟insert方法也很类似。

  其实从这里大家应该明白了阻塞队列的实现原理,事实它和我们用Object.wait()、Object.notify()和非阻塞队列实现生产者-消费者的思路类似,只不过它把这些工作一起集成到了阻塞队列中实现

四、示例和使用场景

  下面先使用Object.wait()和Objct.notify()、非阻塞队列实现生产者-消费者模式:

 1 package com.meng.javalanguage.producerConsumer;
 2 
 3 import java.util.PriorityQueue;
 4 
 5 public class Test {
 6     private int queueSize = 10;
 7     private PriorityQueue<Integer> queue = new PriorityQueue<Integer>(queueSize);
 8     
 9     public static void main(String[] args) {
10         Test test = new Test();
11         Producer producer = test.new Producer();
12         Consumer consumer = test.new Consumer();
13         
14         
15         producer.start();
16         consumer.start();
17     }
18     
19     class Consumer extends Thread {
20         
21         @Override
22         public void run() {
23             consume();
24         }
25         
26         private void consume() {
27             while(true) {
28                 synchronized (queue) {
29                     while(queue.size() == 0) {
30                         try {
31                             System.out.println("队列空,等待数据");
32                             queue.wait();
33                         }catch (InterruptedException ie) {
34                             ie.printStackTrace();
35                             queue.notify();
36                             
37                         }
38                     }
39                     
40                     queue.poll();    // 每次移走队首元素
41                     queue.notify();
42                     System.out.println("从队列取走一个元素,队列剩余" + queue.size() + "个元素");
43                 }
44             }
45         }
46     }
47     
48     class Producer extends Thread {
49         
50         @Override
51         public void run() {
52             produce();
53         }
54         
55         private void produce() {
56             while(true) {
57                 synchronized (queue) {
58                     while(queue.size() == queueSize) {
59                         try {
60                             System.out.println("队列满,等待有空余空间");
61                             queue.wait();
62                         }catch (InterruptedException ie) {
63                             ie.printStackTrace();
64                             queue.notify();
65                         }
66                     }
67                     
68                     queue.offer(1);        // 每次插入一个元素
69                     queue.notify();
70                     System.out.println("向队列中插入一个元素,队列剩余空间:" + (queueSize - queue.size()));
71                 }
72             }
73         }
74         
75     }
76 }

  这个是经典的生产者-消费者模式,通过阻塞队列和Object.wait()和Object.notify()实现,wait()和notify()主要用来实现线程间通信。

  具体的线程间通信方式(wait和notify的使用)在后续文章中会讲述到。

  下面是阻塞队列实现的生产者-消费者模式:

 1 package com.meng.javalanguage.producerConsumer;
 2 
 3 import java.util.concurrent.ArrayBlockingQueue;
 4 
 5 public class Test1 {
 6 
 7     private int queueSize = 10;
 8     private ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(queueSize);
 9     
10     public static void main(String[] args) {
11         Test1 test1 = new Test1();
12         Producer producer = test1.new Producer();
13         Consumer consumer = test1.new Consumer();
14         
15         producer.start();
16         consumer.start();
17     }
18     
19     
20     class Consumer extends Thread {
21         
22         @Override
23         public void run() {
24             cunsume();
25         }
26         
27         private void cunsume() {
28             while(true) {
29                 try {
30                     queue.take();    // 该方法会抛出异常,需在try...catch块中执行
31                     System.out.println("从队列中取走一个元素,队列剩余" + queue.size() + "个元素");
32                 }catch (InterruptedException ie) {
33                     ie.printStackTrace();
34                 }
35             }
36         }
37     }
38     
39     class Producer extends Thread {
40         
41         @Override
42         public void run() {
43             produce();
44         }
45         
46         private void produce() {
47             while(true) {
48                 try {
49                     queue.put(1);    // 该方法会抛出异常,需要try...catch块中执行
50                     System.out.println("向队列中插入一个元素,队列剩余空间" + (queueSize - queue.size()));
51                 }catch (InterruptedException ie) {
52                     ie.printStackTrace();
53                 }
54             }
55         }
56     }
57 }

  有没有发现,使用阻塞队列代码要简单得多,不需要再单独考虑同步和线程间通信的问题。

  在并发编程中,一般推荐使用阻塞队里,这样实现可以尽量地避免程序出现意外的错误。

  阻塞队列使用最经典的场景就是socket客户端数据的读取和解析,读取数据的线程不断将数据放入队列,然后解析线程不断从队列取数据解析。还有其它类似的场景,只要符合生产者-消费者模型的都可以使用阻塞队列。

  转载自《Java并发编程:阻塞队列

猜你喜欢

转载自www.cnblogs.com/codingmengmeng/p/9996827.html