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)。个人认为,是为了让语义更加清楚,即在方法内就可以看到变量的属性,不需要跳到类的开头查看。
- Chapter 7 生产者消费者之ArrayBlockingQueue实现
- 利用ArrayBlockingQueue实现生产者-消费者
- Chapter 6 生产者消费者之Condition实现
- 生产者消费者模型 ArrayBlockingQueue
- Chapter 5 生产者消费者系列之传统实现
- 生产者消费者模型(二)-引入ArrayBlockingQueue
- 生产者消费者模型(二)-引入ArrayBlockingQueue
- 基于ArrayBlockingQueue的生产者和消费者
- 用阻塞队列ArrayBlockingQueue或LinkedBlockingQueue实现实现生产者与消费者
- 生产者消费者问题简单解决之ArrayBlockingQueue的详解与使用
- .net实现--多线程之生产者/消费者问题
- 生产者消费者问题之Java线程实现
- 多线程编程之生产者消费者(java实现)
- MQTT协议之生产者消费者实现
- 生产者与消费者之实现(wait、notify)
- 生产者消费者之Java/python实现
- vc实现生产者消费者
- 生产者消费者---C实现
- oracle安装报错 windows找不到文件‘http:/127.0.0.1:%HTTPPORT%/apex/f?p=4950’.请确定文件名是否正确后,再试一次
- sed命令详解
- Paintball(dfs判断连通)
- Android中dip、dp、sp、pt和px的区别
- iOS UI 第三课 父子视图
- Chapter 7 生产者消费者之ArrayBlockingQueue实现
- cf 417 C Football
- 关于大学
- Windows核心编程 第九章 线程与内核对象的同步(上)
- python中使用xlrd、xlwt操作excel表格详解
- jquery事件delegate()方法用法详解
- Android中ListView复用导致布局错乱的解决方案
- 【学习笔记】第七章 复用类
- 有序数组旋转后数组最小值