生产者消费者的模型作用

  1. 通过平衡生产者的生产能力和消费者的消费能力来提升整个系统的运行效率,这是生产者消费者模型最重要的作用。
  2. 解耦,这是生产者消费者模型附带的作用,解耦意味着生产者和消费者之间的联系少,联系越少越可以独自发展

使用阻塞队列来实现

  1. package yunche.test.producer;
  2.  
  3. import java.util.Random;
  4. import java.util.concurrent.BlockingQueue;
  5.  
  6. /**
  7. * @ClassName: Producer
  8. * @Description: 生产者
  9. * @author: yunche
  10. * @date: 2018/08/26
  11. */
  12. public class Producer implements Runnable
  13. {
  14.  
  15. private final BlockingQueue<Integer> queue;
  16.  
  17. public Producer(BlockingQueue q)
  18. {
  19. this.queue = q;
  20. }
  21.  
  22. @Override
  23. public void run()
  24. {
  25. try
  26. {
  27. while(true)
  28. {
  29. //模拟耗时1s
  30. Thread.sleep(1000);
  31. queue.put(produce());
  32. }
  33. }
  34. catch (InterruptedException e)
  35. {
  36. e.printStackTrace();
  37. }
  38. }
  39.  
  40. private int produce()
  41. {
  42. int n = new Random().nextInt(10000);
  43. System.out.println("Thread: " + Thread.currentThread().getName() + " produce: " + n);
  44. return n;
  45. }
  46. }
  47.  
  48. package yunche.test.producer;
  49.  
  50. import java.util.concurrent.BlockingQueue;
  51.  
  52. /**
  53. * @ClassName: Consumer
  54. * @Description: 消费者
  55. * @author: yunche
  56. * @date: 2018/08/26
  57. */
  58. public class Consumer implements Runnable
  59. {
  60. private final BlockingQueue<Integer> queue;
  61.  
  62. public Consumer(BlockingQueue q)
  63. {
  64. this.queue = q;
  65. }
  66.  
  67. @Override
  68. public void run()
  69. {
  70. while (true)
  71. {
  72. try
  73. {
  74. //模拟耗时
  75. Thread.sleep(2000);
  76. consume(queue.take());
  77. }
  78. catch (InterruptedException e)
  79. {
  80. e.printStackTrace();
  81. }
  82. }
  83.  
  84. }
  85.  
  86. private void consume(Integer n)
  87. {
  88. System.out.println("Thread:" + Thread.currentThread().getName() + " consume: " + n);
  89. }
  90. }
  91.  
  92. package yunche.test.producer;
  93.  
  94. import java.util.concurrent.ArrayBlockingQueue;
  95. import java.util.concurrent.BlockingQueue;
  96.  
  97. /**
  98. * @ClassName: Main
  99. * @Description: 测试类
  100. * @author: yunche
  101. * @date: 2018/08/26
  102. */
  103. public class Main
  104. {
  105. public static void main(String[] args)
  106. {
  107. BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(100);
  108. Producer p = new Producer(queue);
  109. Consumer c1 = new Consumer(queue);
  110. Consumer c2 = new Consumer(queue);
  111.  
  112. Thread producer = new Thread(p);
  113. producer.setName("生产者线程");
  114. Thread consumer1 = new Thread(c1);
  115. consumer1.setName("消费者1");
  116. Thread consumer2 = new Thread(c2);
  117. consumer2.setName("消费者2");
  118.  
  119. producer.start();
  120. consumer1.start();
  121. consumer2.start();
  122.  
  123. }
  124. }

使用wait-notify来实现

  1. package yunche.test.producer;
  2.  
  3. import java.util.LinkedList;
  4. import java.util.Random;
  5.  
  6. /**
  7. * @ClassName: Producer
  8. * @Description: 生产者
  9. * @author: yunche
  10. * @date: 2018/08/26
  11. */
  12. public class Producer implements Runnable
  13. {
  14.  
  15. private final LinkedList<Integer> list;
  16.  
  17. /**
  18. * 缓冲区大小
  19. */
  20. private final int maxSize;
  21.  
  22. public Producer(LinkedList list, int size)
  23. {
  24. this.list = list;
  25. maxSize =size;
  26. }
  27.  
  28. @Override
  29. public void run()
  30. {
  31. try
  32. {
  33. while(true)
  34. {
  35. //模拟耗时1s
  36. Thread.sleep(1000);
  37. synchronized (list)
  38. {
  39. if(list.size()==maxSize)
  40. {
  41. System.out.println("缓冲区已满,正在等待消费者消费..." + System.currentTimeMillis());
  42. list.wait();
  43. }
  44. else
  45. {
  46. list.add(produce());
  47. list.notifyAll();
  48. }
  49. }
  50.  
  51. }
  52. }
  53. catch (InterruptedException e)
  54. {
  55. e.printStackTrace();
  56. }
  57. }
  58.  
  59. private int produce()
  60. {
  61. int n = new Random().nextInt(10000);
  62. System.out.println("Thread: " + Thread.currentThread().getName() + " produce: " + n);
  63. return n;
  64. }
  65. }
  66.  
  67. package yunche.test.producer;
  68.  
  69. import java.util.Date;
  70. import java.util.LinkedList;
  71.  
  72. /**
  73. * @ClassName: Consumer
  74. * @Description: 消费者
  75. * @author: yunche
  76. * @date: 2018/08/26
  77. */
  78. public class Consumer implements Runnable
  79. {
  80. private final LinkedList<Integer> list;
  81.  
  82. public Consumer(LinkedList list)
  83. {
  84. this.list = list;
  85. }
  86.  
  87. @Override
  88. public void run()
  89. {
  90. while (true)
  91. {
  92. try
  93. {
  94. synchronized(list)
  95. {
  96. //模拟耗时
  97. Thread.sleep(1000);
  98. if(list.isEmpty())
  99. {
  100. System.out.println("缓冲区已空,正在等待生产者生产..." + System.currentTimeMillis() + Thread.currentThread().getName());
  101. list.wait();
  102. }
  103. else
  104. {
  105. consume(list.poll());
  106. list.notifyAll();
  107. }
  108. }
  109.  
  110. }
  111. catch (InterruptedException e)
  112. {
  113. e.printStackTrace();
  114. }
  115. }
  116.  
  117. }
  118.  
  119. private void consume(Integer n)
  120. {
  121. System.out.println("Thread:" + Thread.currentThread().getName() + " consume: " + n);
  122. }
  123. }
  124.  
  125. package yunche.test.producer;
  126.  
  127. import java.util.ArrayList;
  128. import java.util.LinkedList;
  129. import java.util.List;
  130.  
  131. /**
  132. * @ClassName: Main
  133. * @Description: 测试类
  134. * @author: yunche
  135. * @date: 2018/08/26
  136. */
  137. public class Main
  138. {
  139. public static void main(String[] args)
  140. {
  141. LinkedList<Integer> list = new LinkedList<>();
  142. Producer p = new Producer(list, 10);
  143. Consumer c1 = new Consumer(list);
  144. Consumer c2 = new Consumer(list);
  145.  
  146. Thread producer = new Thread(p);
  147. producer.setName("生产者线程");
  148. Thread consumer1 = new Thread(c1);
  149. consumer1.setName("消费者1");
  150. Thread consumer2 = new Thread(c2);
  151. consumer2.setName("消费者2");
  152.  
  153. producer.start();
  154. consumer1.start();
  155. consumer2.start();
  156.  
  157. }
  158. }

参考资料

  Java面试题

用Java写一个生产者-消费者队列的更多相关文章

  1. kafka集群搭建和使用Java写kafka生产者消费者

    1 kafka集群搭建 1.zookeeper集群  搭建在110, 111,112 2.kafka使用3个节点110, 111,112 修改配置文件config/server.properties ...

  2. java+反射+多线程+生产者消费者模式+读取xml(SAX)入数据库mysql-【费元星Q9715234】

    java+反射+多线程+生产者消费者模式+读取xml(SAX)入数据库mysql-[费元星Q9715234] 说明如下,不懂的问题直接我[费元星Q9715234] 1.反射的意义在于不将xml tag ...

  3. 第23章 java线程通信——生产者/消费者模型案例

    第23章 java线程通信--生产者/消费者模型案例 1.案例: package com.rocco; /** * 生产者消费者问题,涉及到几个类 * 第一,这个问题本身就是一个类,即主类 * 第二, ...

  4. java多线程模拟生产者消费者问题,公司面试常常问的题。。。

    package com.cn.test3; //java多线程模拟生产者消费者问题 //ProducerConsumer是主类,Producer生产者,Consumer消费者,Product产品 // ...

  5. Java并发之:生产者消费者问题

    生产者消费者问题是Java并发中的常见问题之一,在实现时,一般可以考虑使用juc包下的BlockingQueue接口,至于具体使用哪个类,则就需要根据具体的使用场景具体分析了.本文主要实现一个生产者消 ...

  6. java多线程解决生产者消费者问题

    import java.util.ArrayList; import java.util.List; /** * Created by ccc on 16-4-27. */ public class ...

  7. Java多线程同步——生产者消费者问题

    这是马士兵老师的Java视频教程里的一个生产者消费者问题的模型 public class ProduceConsumer{ public static void main(String[] args) ...

  8. java模拟实现生产者---消费者问题

    本文章为小编原创,请尊重文章的原创性,转载请注意写明转载来源:http://blog.csdn.net/u012116457 已知技术參数: 生产者消费者问题,描写叙述一组生产者向一组消费者提供产品/ ...

  9. C# 实现生产者消费者队列

    开发过程中经常会碰到这样的场景:需要从一个地方获取一些数据,然后处理数据并将其保存在数据库中. 1 2 3 4 5 6 7 8 9 10 private void FetchData() {} pri ...

随机推荐

  1. VC++ 模拟&quot;CLICK事件&quot;关闭指定窗体

    今天改动一个工具时遇到一个有意思的问题,打开某个窗体时弹出一些不相关的窗体.须要用户自己去手动点击后才干继续.保证不了自己主动处理,如今解说决方案记录一下,例如以下 主要使用windows提供的Fin ...

  2. [翻译]NUnit--Getting Started(二)

    Getting Started with NUnit 如果你打算开始学习,到下载页面选择一个NUnit版本.安装页面包含了安装说明. 开始NUnit阅读Quick Start页面.验证了一个C#银行应 ...

  3. 洛谷P1719 最大加权矩形

    题目描述 为了更好的备战NOIP2013,电脑组的几个女孩子LYQ,ZSC,ZHQ认为,我们不光需要机房,我们还需要运动,于是就决定找校长申请一块电脑组的课余运动场地,听说她们都是电脑组的高手,校长没 ...

  4. codeforces AIM Tech Round 4 div 2

    A:开个桶统计一下,但是不要忘记k和0比较大小 #include<bits/stdc++.h> using namespace std; ]; ]; int main() { int k; ...

  5. RabbitMQ学习之Work Queues(2)

    目录: 轮询调度(Round-robin dispatching):即依次分配分配任务给worker. 消息答复(Message acknowledgement):在consumer处理完之后,进行消 ...

  6. mongodb海量数据CRUD优化

    1. 批量保存优化 避免一条一条查询,采用bulkWrite, 基于ReplaceOneModel,启用upsert: public void batchSave(List<?> spoT ...

  7. 数据结构之单链表(C实现)

    list.h #ifndef LIST_H #define LIST_H #include <iostream> #include <stdio.h> #include < ...

  8. [C和指针] 4-语句、5-操作符和表达式

    第4章 语句 4.1 表达式语句 C并不存在专门的"赋值语句",赋值就是一种操作,就像加法和减法一样,所以赋值就在表达式内进行. 你只要在表达式后面加上一个分号,就可以把表达式转变 ...

  9. EditText(8)EditText中drawableRight图片的点击事件

    参考: http://stackoverflow.com/questions/3554377/handling-click-events-on-a-drawable-within-an-edittex ...

  10. 转 DOS(CMD)下批处理换行问题/命令行参数换行 arg ms-dos

    DOS(CMD)下批处理换行问题本人经常写一些DOS批处理文件,由于批处理中命令的参考较多且长,写在一行太不容易分辨,所以总想找个办法把一条命令分行来写,今天终于试成功两种方法.一.在CMD下,可以用 ...