前言

最近面试比较多,发现生产消费者模型在各公司面试的过程中问的还是比较多的,记录一下常见JAVA实现生产者消费模型的代码

思路

我们通过三种模式来实现

  1. 通过wait和notify
  2. 通过Lock和Condition
  3. 通过JAVA内部的阻塞队列ArrayBlockingQueue

代码

  1. wait和notify

通过synchronized来保证线程安全,在消息满或者不足的时候wait进行阻塞,然后notifyAll来通知其他监听

static class Storage {

        private Queue<Integer> queue;

        private Integer max;

        public Storage(Queue<Integer> queue, Integer max) {
this.queue = queue;
this.max = max;
} private synchronized void produce(Integer msg) { while (queue.size() > max) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.offer(msg);
this.notifyAll();
} private synchronized Integer consume() { while (queue.size() == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Integer result = queue.poll();
this.notifyAll();
return result;
}
}
  1. Lock和Condition

通过Lock来保证线程安全,通过Condition来实现阻塞和通信,在消息队列满的时候,通过notFull的wait和notEmpty的signalAll来阻塞当前生产者并且通知消费者来消费消息,消息队列空的时候同理

 static class Storage {

        private Queue<Integer> queue;

        private Integer max;

        private Lock lock;

        private Condition notEmpty;

        private Condition notFull;

        public Storage(Queue<Integer> queue, Integer max) {
this.queue = queue;
this.max = max;
lock = new ReentrantLock();
notEmpty = lock.newCondition();
notFull = lock.newCondition();
} private void produce(Integer msg) { lock.lock();
try {
while (queue.size() > max) {
notFull.await();
}
queue.offer(msg);
notEmpty.signalAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
} } private synchronized Integer consume() {
lock.lock();
Integer result = null;
try {
while (queue.size() == 0) {
notEmpty.await();
}
result = queue.poll();
notFull.signalAll();
} catch (Exception e) {
e.printStackTrace(); } finally {
lock.unlock();
}
return result;
}
}
  1. 通过JAVA的实现类ArrayBlockingQueue

ArrayBlockingQueue是一个阻塞队列,在队列满的时候put会阻塞,空的时候take也会阻塞,其内部实现也是基于Lock和Condition来实现的

 static class Storage {

        private ArrayBlockingQueue<Integer> queue;

        public Storage(Integer max) {
this.queue = new ArrayBlockingQueue<>(max);
} private void produce(Integer msg) {
try {
queue.put(msg);
} catch (InterruptedException e) {
e.printStackTrace();
}
} private Integer consume() {
try {
return queue.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
}

测试

生产线程:

 static class Producer implements Runnable {

        private Storage storage;

        private Integer msg;

        public Producer(Storage storage, Integer msg) {
this.storage = storage;
this.msg = msg;
} @Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
storage.produce(msg);
System.out.println("this is producer :" + msg);
}
}
}

消费者线程:

 static class Consumer implements Runnable {

        private Storage storage;

        public Consumer(Storage storage) {
this.storage = storage;
} @Override
public void run() { while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("this is consumer:" + storage.consume());
}
}
}

测试用例:通过多个生产者消费者线程来模拟,执行代码后可验证生产和消费的有序进行

 public static void main(String[] args) {

        Storage storage = new Storage(2);

        Producer producer = new Producer(storage, 1);
Producer producer2 = new Producer(storage, 2);
Producer producer3 = new Producer(storage, 3); new Thread(producer).start();
new Thread(producer2).start();
new Thread(producer3).start(); Consumer consumer1 = new Consumer(storage);
Consumer consumer2 = new Consumer(storage);
Consumer consumer3 = new Consumer(storage); new Thread(consumer1).start();
new Thread(consumer2).start();
new Thread(consumer3).start();
}

JAVA实现生产消费者模型的更多相关文章

  1. Java生产消费者模型——代码解析

    我们将生产者.消费者.库存.和调用线程的主函数分别写进四个类中,通过抢夺非线程安全的数据集合来直观的表达在进行生产消费者模型的过程中可能出现的问题与解决办法. 我们假设有一个生产者,两个消费者来共同抢 ...

  2. Linux——多线程下解决生产消费者模型

    我们学习了操作系统,想必对生产消费者问题都不陌生.作为同步互斥问题的一个经典案例,生产消费者模型其实是解决实际问题的基础模型,解决很多的实际问题都会依赖于它.而此模型要解决最大的问题便是同步与互斥.而 ...

  3. Python进阶----进程之间通信(互斥锁,队列(参数:timeout和block),), ***生产消费者模型

    Python进阶----进程之间通信(互斥锁,队列(参数:timeout和block),), ***生产消费者模型 一丶互斥锁 含义: ​ ​ ​ 每个对象都对应于一个可称为" 互斥锁&qu ...

  4. Python之queue模块以及生产消费者模型

    队列 队列类似于一条管道,元素先进先出,进put(arg),取get() 有一点需要注意的是:队列都是在内存中操作,进程退出,队列清空,另外,队列也是一个阻塞的形态. 队列分类 队列有很多中,但都依赖 ...

  5. Python并发编程04 /多线程、生产消费者模型、线程进程对比、线程的方法、线程join、守护线程、线程互斥锁

    Python并发编程04 /多线程.生产消费者模型.线程进程对比.线程的方法.线程join.守护线程.线程互斥锁 目录 Python并发编程04 /多线程.生产消费者模型.线程进程对比.线程的方法.线 ...

  6. Python - Asyncio模块实现的生产消费者模型

    [原创]转载请注明作者Johnthegreat和本文链接 在设计模式中,生产消费者模型占有非常重要的地位,这个模型在现实世界中也有很多有意思的对应场景,比如做包子的人和吃包子的人,当两者速度不匹配时, ...

  7. Java 实现生产者 – 消费者模型

    转自:http://www.importnew.com/27063.html 考查Java的并发编程时,手写“生产者-消费者模型”是一个经典问题.有如下几个考点: 对Java并发模型的理解 对Java ...

  8. Python——Queue模块以及生产消费者模型

    1.了解Queue Queue是python标准库中的线程安全的队列(FIFO)实现,提供了一个适用于多线程编程的先进先出的数据结构,即队列,用来在生产者和消费者线程之间的信息传递 |queue.Qu ...

  9. Java完成生产者消费者模型

    生产者和消费者模型,是多线程中的典型模型,这里使用Java完成该模型 ServerTest.java 生产者代码 package com.orange.threadmodel; import java ...

随机推荐

  1. Java 枚举和类的区别

    枚举 包含一组常量合法的数据,不能创建枚举实例,也不能进行扩展. package com.jtfr.demo; public enum Week { MONDAY, TUESDAY, WEDNESDA ...

  2. 【Java学习笔记】2015.1.5

    1.classpath中的“.”表示当前的路径,所以配置classpath时要注意不能忘了“.”.如果不注意,会出现cmd下运行程序时,.java文件可以编译但是不能运行: 一般的classpath配 ...

  3. Es学习第六课, ES基本搜索_search

    前面几课ES的基本概念.安装和分词都讲过了,下面我们就来实战一下ES的核心功能-搜索,这节课我们主要讲的是基本搜索 _search(注意:ES的关键字都要加前缀_,所以我们在定义索引.类型名称时不要带 ...

  4. VS2013+phread.h环境配置

    原文链接:http://blog.csdn.net/qianchenglenger/article/details/16907821 本人使用的是windows7 旗舰版64位 目前用的是pthrea ...

  5. 职责链模式ChainOfResponsibility

    原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/11407114.html  1.定义 使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合 ...

  6. Arthas 开源一周年,GitHub Star 16 K ,我们一直在坚持什么?

    缘起 最近看到一个很流行的标题,<开源XX年,star XXX,我是如何坚持的>.看到这样的标题,忽然发觉 Arthas 从 2018 年 9 月开源以来,刚好一年了,正好在这个秋高气爽的 ...

  7. zabbix 如何监控php-fpm?

    zabbix监控php-fpm主要是通过nginx配置php-fpm的状态输出页面,在正则取值.要nginx能输出php-fpm的状态首先要先修改php-fpm的配置,没有开启nginx是没有法输出p ...

  8. PDO防 SQL注入攻击 原理分析 以及 使用PDO的注意事项

    我们都知道,只要合理正确使用PDO(PDO一是PHP数据对象(PHP Data Object)的缩写),可以基本上防止SQL注入的产生,本文主要回答以下几个问题: 为什么要使用PDO而不是mysql_ ...

  9. VMware 虚拟机NAT模式如何设置网络连接,从头到尾全过程~!!

    一.首先查看自己的虚拟机服务有没有开启,选择电脑里面的服务查看: 1.计算机点击右键选择管理  2.进入管理选择VM开头的服务如果没有开启的话就右键开启  二.虚拟机服务开启后就查看本地网络虚拟机的网 ...

  10. 线程同步(基于java)

    java线程 同步与异步 线程池 1)多线程并发时,多个线程同时请求同一个资源,必然导致此资源的数据不安全,A线程修改了B线 程的处理的数据,而B线程又修改了A线程处理的数理.显然这是由于全局资源造成 ...