Chapter 7 生产者消费者之ArrayBlockingQueue实现

来源:互联网 发布:mac如何卸载迅雷插件 编辑:程序博客网 时间:2024/06/05 14:24

1 概述

在Java1.5中提供了很多并发类,其中ArrayBlockingQueue就是其中的一个。ArrayBlockingQueue为BlockingQueue的实现类,常用的阻塞队列。使用这个类能很方便的实现生产者和消费者的经典模式。其提供的阻塞式方法put与take能屏弊同步的细节。并且,在前面的几篇wiki当中都是默认实现生产单个商品的,如果需要实现生产多个商品(即容许商品堆积),使用ArrayBlockingQueue就十分的方便,只需要控制队列的容量就可以了。

2 具体实现

2.1 生产单个商品

和上几篇blog类似,生产单个商品不容许商品堆积,生产了一个必须等待消费者消费完才能继续生产。使用ArrayBlockingQueue使用的代码如下。

import java.util.Random;import java.util.concurrent.ArrayBlockingQueue; /** * Created by fubinhe on 16/10/1. */public class ArrayBlockingQueueDemo {    public static void main(String[] args) {        ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(1);        for (int i = 0; i < 2; ++i) {            new Thread(new Producer(queue)).start();            new Thread(new Consumer(queue)).start();        }    }}  class Producer implements Runnable {     private ArrayBlockingQueue<Integer> queue;     public Producer(ArrayBlockingQueue<Integer> queue) {        this.queue = queue;    }     @Override    public void run() {        while (true) {            produce();        }    }     private void produce() {        try {            int x = new Random().nextInt(1000);            queue.put(x);            System.out.println(Thread.currentThread().getName() + " produced..." + x);        } catch (InterruptedException e) {            e.printStackTrace();        }    }} class Consumer implements Runnable {     private ArrayBlockingQueue<Integer> queue;     public Consumer(ArrayBlockingQueue<Integer> queue) {        this.queue = queue;    }     @Override    public void run() {        while (true) {            consume();        }    }     private void consume() {        try {            int x = queue.take();            System.out.println(Thread.currentThread().getName() + " consumed......" + x);        } catch (InterruptedException e) {            e.printStackTrace();        }    }}

程序的运行结果如下图,和上几篇blog的效果类似。不过仔细观察下图,可以发现有时候消费的打印语句出现在了生产的打印语句的前面,出现这种情况的原因是,打印语句并没有包含在synchronized语句里面,所有不能实现打印语句的并发。

2.2 生产多个商品

生产多个商品和生产多个商品的原理类似,这就是为什么上几篇wiki都是以生产单个商品为例进行讨论的。其实,容许商品堆积更加符合现实生活。如果,利用传统方法实现多个商品的生产,需要维护一个数组或者List容器,并判断当前的容量进行相关的操作。但是使用ArrayBlockingQueue就可以屏蔽这些细节。具体的实现参考下面的代码。

import java.util.Random;import java.util.concurrent.ArrayBlockingQueue; /** * Created by fubinhe on 16/10/1. */public class ArrayBlockingQueueDemo {    public static void main(String[] args) {        ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(5);        for (int i = 0; i < 2; ++i) {            new Thread(new Producer(queue)).start();            new Thread(new Consumer(queue)).start();        }    }} class Producer implements Runnable {     private ArrayBlockingQueue<Integer> queue;     public Producer(ArrayBlockingQueue<Integer> queue) {        this.queue = queue;    }     @Override    public void run() {        while (true) {            produce();        }    }     private void produce() {        try {            int x = new Random().nextInt(1000);            queue.put(x);            System.out.println(Thread.currentThread().getName() + " produced..." + x + ", size..." + queue.size());        } catch (InterruptedException e) {            e.printStackTrace();        }    }} class Consumer implements Runnable {     private ArrayBlockingQueue<Integer> queue;     public Consumer(ArrayBlockingQueue<Integer> queue) {        this.queue = queue;    }     @Override    public void run() {        while (true) {            consume();        }    }     private void consume() {        try {            int x = queue.take();            System.out.println(Thread.currentThread().getName() + " consumed......" + x + ", size......" + queue.size());        } catch (InterruptedException e) {            e.printStackTrace();        }    }}

这里试图打印出队列当前的容量,程序的运行结果如下图。可以发现第二行的结果中队列的容量是1,理论上应该是0。出现这种情况的原因还是打印语句并没有同步造成的。也就是说ArrayBlockingQueue本身是同步互斥的,但是打印语句没有进行同步。这和操作Vector类有点像,具体可以参考:Chapter 3 Vector类还需要同步吗。

3 ArrayBlockingQueue重要方法

ArrayBlockingQueue提供了对队列进行操作的一些重要方法,这些方法主要分为两大类,即读操作和写操作,下面简单介绍一下这些方法:

3.1 读操作

peek(): 返回队首的元素,如果为空返回null

poll(): 这个方法和上面方法类似,只不过同时将队首元素删除

poll(long timeout, TimeUnit unit): 这个方法和上面方法类似,只不过当队列为空时会等待一段时间

take(E e): 获取队首的元素,如果队列为空则一直等待(即阻塞式)

3.2 写操作

add(E e): 将元素e插入队列,如果当前队列未满则立即插入返回true,否则抛出IllegalStateException

offer(E e): 将元素e插入队列,如果当前队列未满则立即插入返回true,否则插入失败返回false

offer(E e, long timeout, TimeUnit unit): 这个方法和上面方法类似,只不过有个等待时间

put(E e): 将元素e插入队列,如果队列满了则一直等待(即阻塞式)

4 源码分析

public void put(E e) throws InterruptedException {    checkNotNull(e);    final ReentrantLock lock = this.lock;    lock.lockInterruptibly();    try {        while (count == items.length)            notFull.await();        insert(e);    } finally {        lock.unlock();    }} 
public E take() throws InterruptedException {    final ReentrantLock lock = this.lock;    lock.lockInterruptibly();    try {        while (count == 0)            notEmpty.await();        return extract();    } finally {        lock.unlock();    }}

可以看出这两个方法中关于锁的获取与释放以及线程的等待和唤醒与Chapter 6 生产者消费者之Condition实现中类似。其中this.lock是ArrayBlockingQueue的一个ReentrantLock对象,而notFull和notEmpty是绑定在这个锁上的两个Condition对象。而put方法中的insert方法以及take方法中的extract方法是对队列的操作,具体可以参考源代码。


P.S. 在这两个方法的最开始的那一行代码:final ReentrantLock lock = this.lock,很迷惑,为什么要讲成员变量赋值为局部变量呢。其实,在j.u.c包中,作者Doug Lea多次用到了这种手法,关于其这样的做的原因,网上有很多说法(参考:http://blog.csdn.net/walkerjong/article/details/51537759)。个人认为,是为了让语义更加清楚,即在方法内就可以看到变量的属性,不需要跳到类的开头查看。

0 0
原创粉丝点击