生产者消费者的模型作用

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

使用阻塞队列来实现

package yunche.test.producer;

import java.util.Random;
import java.util.concurrent.BlockingQueue; /**
* @ClassName: Producer
* @Description: 生产者
* @author: yunche
* @date: 2018/08/26
*/
public class Producer implements Runnable
{ private final BlockingQueue<Integer> queue; public Producer(BlockingQueue q)
{
this.queue = q;
} @Override
public void run()
{
try
{
while(true)
{
//模拟耗时1s
Thread.sleep(1000);
queue.put(produce());
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
} private int produce()
{
int n = new Random().nextInt(10000);
System.out.println("Thread: " + Thread.currentThread().getName() + " produce: " + n);
return n;
}
} package yunche.test.producer; import java.util.concurrent.BlockingQueue; /**
* @ClassName: Consumer
* @Description: 消费者
* @author: yunche
* @date: 2018/08/26
*/
public class Consumer implements Runnable
{
private final BlockingQueue<Integer> queue; public Consumer(BlockingQueue q)
{
this.queue = q;
} @Override
public void run()
{
while (true)
{
try
{
//模拟耗时
Thread.sleep(2000);
consume(queue.take());
}
catch (InterruptedException e)
{
e.printStackTrace();
}
} } private void consume(Integer n)
{
System.out.println("Thread:" + Thread.currentThread().getName() + " consume: " + n);
}
} package yunche.test.producer; import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue; /**
* @ClassName: Main
* @Description: 测试类
* @author: yunche
* @date: 2018/08/26
*/
public class Main
{
public static void main(String[] args)
{
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(100);
Producer p = new Producer(queue);
Consumer c1 = new Consumer(queue);
Consumer c2 = new Consumer(queue); Thread producer = new Thread(p);
producer.setName("生产者线程");
Thread consumer1 = new Thread(c1);
consumer1.setName("消费者1");
Thread consumer2 = new Thread(c2);
consumer2.setName("消费者2"); producer.start();
consumer1.start();
consumer2.start(); }
}

使用wait-notify来实现

package yunche.test.producer;

import java.util.LinkedList;
import java.util.Random; /**
* @ClassName: Producer
* @Description: 生产者
* @author: yunche
* @date: 2018/08/26
*/
public class Producer implements Runnable
{ private final LinkedList<Integer> list; /**
* 缓冲区大小
*/
private final int maxSize; public Producer(LinkedList list, int size)
{
this.list = list;
maxSize =size;
} @Override
public void run()
{
try
{
while(true)
{
//模拟耗时1s
Thread.sleep(1000);
synchronized (list)
{
if(list.size()==maxSize)
{
System.out.println("缓冲区已满,正在等待消费者消费..." + System.currentTimeMillis());
list.wait();
}
else
{
list.add(produce());
list.notifyAll();
}
} }
}
catch (InterruptedException e)
{
e.printStackTrace();
}
} private int produce()
{
int n = new Random().nextInt(10000);
System.out.println("Thread: " + Thread.currentThread().getName() + " produce: " + n);
return n;
}
} package yunche.test.producer; import java.util.Date;
import java.util.LinkedList; /**
* @ClassName: Consumer
* @Description: 消费者
* @author: yunche
* @date: 2018/08/26
*/
public class Consumer implements Runnable
{
private final LinkedList<Integer> list; public Consumer(LinkedList list)
{
this.list = list;
} @Override
public void run()
{
while (true)
{
try
{
synchronized(list)
{
//模拟耗时
Thread.sleep(1000);
if(list.isEmpty())
{
System.out.println("缓冲区已空,正在等待生产者生产..." + System.currentTimeMillis() + Thread.currentThread().getName());
list.wait();
}
else
{
consume(list.poll());
list.notifyAll();
}
} }
catch (InterruptedException e)
{
e.printStackTrace();
}
} } private void consume(Integer n)
{
System.out.println("Thread:" + Thread.currentThread().getName() + " consume: " + n);
}
} package yunche.test.producer; import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List; /**
* @ClassName: Main
* @Description: 测试类
* @author: yunche
* @date: 2018/08/26
*/
public class Main
{
public static void main(String[] args)
{
LinkedList<Integer> list = new LinkedList<>();
Producer p = new Producer(list, 10);
Consumer c1 = new Consumer(list);
Consumer c2 = new Consumer(list); Thread producer = new Thread(p);
producer.setName("生产者线程");
Thread consumer1 = new Thread(c1);
consumer1.setName("消费者1");
Thread consumer2 = new Thread(c2);
consumer2.setName("消费者2"); producer.start();
consumer1.start();
consumer2.start(); }
}

参考资料

  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. libjpeg交叉编译

    下载libjpeg http://libjpeg.sourceforge.net/ 解压tar -zxf jpegsrc.v6b.tar.gz cd jpeg-6b cp /usr/bin/libto ...

  2. ionic2 在执行ionic serve后报 build dev failed: Cannot set property 'fileSystem' of null

    ionic2 真是烦人,因为环境依赖的问题还有网络的问题,不知砸的,项目放一段事件不运行就会出问题. 我一开始是 用 cnpm install安装的依赖,其中也报了错, 然后执行 ionic serv ...

  3. cc1: error: bad value (armv5) for -march= switch【转】

    本文转载自:https://stackoverflow.com/questions/23871924/cc1-error-bad-value-armv5-for-march-switch Ask Qu ...

  4. [疑问] C# 多线程程序,如果在并行程序块中开空间会远远慢于将空间开在并行块之外

    // int[,] label = new int[m, n]; Parallel.For(, thread_num, (n) => { ]; i++) { int[] tmp = new in ...

  5. Joseph问题 (线段树)

    Joseph问题似乎是入门题,就是那个报数出圈的问题,不过它暴力模拟的复杂度是O(nm)的,如果题目的数据范围达到了30000,那就超时了.怎么用线段树维护呢? 我们可以这么考虑,每次我们其实要查询在 ...

  6. Python---NumPy模块---矩阵操作

    1.NumPy访问[数组&矩阵] 2.矩阵的运算 3.NumPy通用函数 4.NumPy矩阵的合并和分割 print "**********Numpy访问(数组&矩阵)*** ...

  7. eclipse maven创建web项目

    记录地址 jdk设置及文件包miss 实例下载地址 创建SSM整合项目 一.使用Eclipse中的maven插件创建web项目 1: 2: 3: 4: 5:maven web项目创建成功.(去掉ind ...

  8. 搞定springboot项目连接远程服务器上kafka遇到的坑以及完整的例子

    版本 springboot 2.1.5.RELEASE kafka 2.2 遇到的坑 用最新的springboot就要用最新的kafka版本! 当我启动云服务器上的zk后,再启动kafka后台日志也没 ...

  9. set && muliset

    #include <set> #include <iostream> #include <cstdio> #include <cctype> using ...

  10. POJ 3608 旋转卡壳

    思路: 旋转卡壳应用 注意点&边  边&边  点&点 三种情况 //By SiriusRen #include <cmath> #include <cstdi ...