Java里的生产者-消费者模型(Producer and Consumer Pattern in Java)
生产者-消费者模型是多线程问题里面的经典问题,也是面试的常见问题。有如下几个常见的实现方法:
1. wait()/notify()
2. lock & condition
3. BlockingQueue
下面来逐一分析。
1. wait()/notify()
第一种实现,利用根类Object的两个方法wait()/notify(),来停止或者唤醒线程的执行;这也是最原始的实现。
public class WaitNotifyBroker<T> implements Broker<T> {
private final Object[] items;
private int takeIndex;
private int putIndex;
private int count;
public WaitNotifyBroker(int capacity) {
this.items = new Object[capacity];
}
@SuppressWarnings("unchecked")
@Override
public T take() {
T tmpObj = null;
try {
synchronized (items) {
while (0 == count) {
items.wait();
}
tmpObj = (T) items[takeIndex];
if (++takeIndex == items.length) {
takeIndex = 0;
}
count--;
items.notify();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return tmpObj;
}
@Override
public void put(T obj) {
try {
synchronized (items) {
while (items.length == count) {
items.wait();
}
items[putIndex] = obj;
if (++putIndex == items.length) {
putIndex = 0;
}
count++;
items.notify();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
这里利用Array构造一个Buffer去存取数据,并利用count, putIndex和takeIndex来保证First-In-First-Out。
如果利用LinkedList来代替Array,相对来说会稍微简单些。
LinkedList的实现,可以参考《Java 7 Concurrency Cookbook》第2章wait/notify。
2. lock & condition
lock & condition,实际上也实现了类似synchronized和wait()/notify()的功能,但在加锁和解锁、暂停和唤醒方面,更加细腻和可控。
在JDK的BlockingQueue的默认实现里,也是利用了lock & condition。此文也详细介绍了怎么利用lock&condition写BlockingQueue,这里换LinkedList再实现一次:
public class LockConditionBroker<T> implements Broker<T> {
private final ReentrantLock lock;
private final Condition notFull;
private final Condition notEmpty;
private final int capacity;
private LinkedList<T> items;
public LockConditionBroker(int capacity) {
this.lock = new ReentrantLock();
this.notFull = lock.newCondition();
this.notEmpty = lock.newCondition();
this.capacity = capacity;
items = new LinkedList<T>();
}
@Override
public T take() {
T tmpObj = null;
lock.lock();
try {
while (items.size() == 0) {
notEmpty.await();
}
tmpObj = items.poll();
notFull.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
return tmpObj;
}
@Override
public void put(T obj) {
lock.lock();
try {
while (items.size() == capacity) {
notFull.await();
}
items.offer(obj);
notEmpty.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
3. BlockingQueue
最后这种方法,也是最简单最值得推荐的。利用并发包提供的工具:阻塞队列,将阻塞的逻辑交给BlockingQueue。
实际上,上述1和2的方法实现的Broker类,也可以视为一种简单的阻塞队列,不过没有标准包那么完善。
public class BlockingQueueBroker<T> implements Broker<T> {
private final BlockingQueue<T> queue;
public BlockingQueueBroker() {
this.queue = new LinkedBlockingQueue<T>();
}
@Override
public T take() {
try {
return queue.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
@Override
public void put(T obj) {
try {
queue.put(obj);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
我们的队列封装了标注包里的LinkedBlockingQueue,十分简单高效。
接下来,就是一个1P2C的例子:
public interface Broker<T> {
T take();
void put(T obj);
}
public class Producer implements Runnable {
private final Broker<Integer> broker;
private final String name;
public Producer(Broker<Integer> broker, String name) {
this.broker = broker;
this.name = name;
}
@Override
public void run() {
try {
for (int i = 0; i < 5; i++) {
broker.put(i);
System.out.format("%s produced: %s%n", name, i);
Thread.sleep(1000);
}
broker.put(-1);
System.out.println("produced termination signal");
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
}
}
public class Consumer implements Runnable {
private final Broker<Integer> broker;
private final String name;
public Consumer(Broker<Integer> broker, String name) {
this.broker = broker;
this.name = name;
}
@Override
public void run() {
try {
for (Integer message = broker.take(); message != -1; message = broker.take()) {
System.out.format("%s consumed: %s%n", name, message);
Thread.sleep(1000);
}
System.out.println("received termination signal");
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
}
}
public class Main {
public static void main(String[] args) {
Broker<Integer> broker = new WaitNotifyBroker<Integer>(5);
// Broker<Integer> broker = new LockConditionBroker<Integer>(5);
// Broker<Integer> broker = new BlockingQueueBroker<Integer>();
new Thread(new Producer(broker, "prod 1")).start();
new Thread(new Consumer(broker, "cons 1")).start();
new Thread(new Consumer(broker, "cons 2")).start();
}
}
除了上述的方法,其实还有很多第三方的并发包可以解决这个问题。例如LMAX Disruptor和Chronicle等
本文完。
参考:
《Java 7 Concurrency Cookbook》
Java里的生产者-消费者模型(Producer and Consumer Pattern in Java)的更多相关文章
- 第23章 java线程通信——生产者/消费者模型案例
第23章 java线程通信--生产者/消费者模型案例 1.案例: package com.rocco; /** * 生产者消费者问题,涉及到几个类 * 第一,这个问题本身就是一个类,即主类 * 第二, ...
- 生产者和消费者模型producer and consumer(单线程下实现高并发)
#1.生产者和消费者模型producer and consumer modelimport timedef producer(): ret = [] for i in range(2): time.s ...
- Java实现多线程生产者消费者模型及优化方案
生产者-消费者模型是进程间通信的重要内容之一.其原理十分简单,但自己用语言实现往往会出现很多的问题,下面我们用一系列代码来展现在编码中容易出现的问题以及最优解决方案. /* 单生产者.单消费者生产烤鸭 ...
- java并发之生产者消费者模型
生产者和消费者模型是操作系统中经典的同步问题.该问题最早由Dijkstra提出,用以演示它提出的信号量机制. 经典的生产者和消费者模型的描写叙述是:有一群生产者进程在生产产品.并将这些产品提供给消费者 ...
- java多线程之生产者消费者模型
public class ThreadCommunication{ public static void main(String[] args) { Queue q = new Queue();//创 ...
- java多线程解决生产者消费者问题
import java.util.ArrayList; import java.util.List; /** * Created by ccc on 16-4-27. */ public class ...
- 如何在 Java 中正确使用 wait, notify 和 notifyAll – 以生产者消费者模型为例
wait, notify 和 notifyAll,这些在多线程中被经常用到的保留关键字,在实际开发的时候很多时候却并没有被大家重视.本文对这些关键字的使用进行了描述. 在 Java 中可以用 wait ...
- java多线程:线程间通信——生产者消费者模型
一.背景 && 定义 多线程环境下,只要有并发问题,就要保证数据的安全性,一般指的是通过 synchronized 来进行同步. 另一个问题是,多个线程之间如何协作呢? 我们看一个仓库 ...
- Java多线程14:生产者/消费者模型
什么是生产者/消费者模型 一种重要的模型,基于等待/通知机制.生产者/消费者模型描述的是有一块缓冲区作为仓库,生产者可将产品放入仓库,消费者可以从仓库中取出产品,生产者/消费者模型关注的是以下几个点: ...
随机推荐
- SpringMVC基本使用
springMVC是一个MVC框架,他控制着请求相应的整个流程,从请求一进入到应用服务器到相应离开,都离不开mvc框架 请求在应用服务器中 先说说请求相应在应用服务器的整个过程 DisptacherS ...
- Jquery实现的简单轮播效果
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- Sharepoint学习笔记—习题系列--70-576习题解析 -(Q121-Q123)
Question 121 You are designing a SharePoint 2010 workflow that will be used to monitor invoices. Th ...
- SQL Server下载安装
参考下载http://www.orsoon.com/Soft/148976.html 安装教程 解压压缩文件,得到安装程序,运行安装程序(如下图) 2..点击左侧的"安装",选择& ...
- C# WinForm修改配置文件
AppConfigPath 配置文件路径 ,注意 是exe运行的相对路径 private static string AppConfigPath = "WinListen.exe.confi ...
- TNS-12541: TNS:no listener TNS-12560 TNS-00511: No listener
为了测试需要,系统管理员帮忙将一台ORACLE数据库服务器克隆到虚拟机上,我上去删除了root.oracle.tomcat账号下的crontab定时作业,然后启动了ORACLE数据库实例,删除 ...
- Oracle触发器原理、创建、修改、删除
本篇主要内容如下: 8.1 触发器类型 8.1.1 DML触发器 8.1.2 替代触发器 8.1.3 系统触发器 8.2 创建触发器 8.2.1 触发器触发次序 8.2.2 创建DML触发器 8.2. ...
- MongoDB学习笔记~为IMongoRepository接口更新指定字段
回到目录 对于MongoDB来说,它的更新建议是对指定字段来说的,即不是把对象里的所有字段都进行update,而是按需去更新,这在性能上是最优的,这当然也是非常容易理解的,我们今天要实现的就是这种按需 ...
- 【hadoop】如何向map和reduce脚本传递参数,加载文件和目录
本文主要讲解三个问题: 1 使用Java编写MapReduce程序时,如何向map.reduce函数传递参数. 2 使用Streaming编写MapReduce程序(C/C++ ...
- hibernate基础dao类
此文章是基于 搭建SpringMVC+Spring+Hibernate平台 功能:数据库的保存.更新.删除:sql.hql查询:分页查询:调用存储过程 创建hibernate基础dao类: BaseD ...