生产者消费者模式 JAVA

来源:互联网 发布:淘宝评价过了怎么截图 编辑:程序博客网 时间:2024/05/20 17:41

生产者消费者:

为什么要用生产者消费者模式

在多线程开发中,如果消费者的消费速度要大于生产者的生产速度,那么消费者必须等待生产者的生产才能继续消费。同样的如果生产者的生产速度大于消费者的消费速度,那么生产者需要等待消费者消费完再继续生产。生产者消费者模式是为了解决生产者消费者不均衡的问题而出现的。

什么是生产者消费者模式

通常设计模式都是高类聚低耦合的特性。因此生产者消费者模式是通过一个容器来解决生产者和消费者的耦合问题。生产者和消费者通过阻塞队列来进行通讯,所以生产者产生的数据放入阻塞队列中,而消费者从阻塞队列中取数据,阻塞队列相当于一个缓冲区,平衡了生产者和消费者的能力。

生产者消费者模式实例

定义一个容量为5的阻塞队列,把消费者和生产者都关联该阻塞队列,使得生产和消费都与阻塞队列进行通讯

消费者类:

import java.util.concurrent.BlockingQueue;////消费者public class Consumer implements Runnable{private BlockingQueue<String> queue;   public Consumer(BlockingQueue<String>  queue) {super();this.queue = queue;}@Overridepublic void run() {while(true){try {Thread.sleep(1000);String temp;temp = queue.take();System.out.println(Thread.currentThread().getName()+" take:"+temp);} catch (Exception e) {e.printStackTrace();}}}}

生产者类:

import java.util.concurrent.BlockingQueue;///生产者public class Producer implements Runnable {BlockingQueue<String> queue;public Producer(BlockingQueue<String> queue) {super();this.queue = queue;}@Overridepublic void run() {while(true){try {Thread.sleep(1000);String temp = Thread.currentThread().getName();System.out.println("I have made a product:"+temp);queue.put(temp);} catch (InterruptedException e) {e.printStackTrace();}}}}

test类:

import java.util.concurrent.BlockingQueue;import java.util.concurrent.LinkedBlockingQueue;public class Test {public  static void main(String args[]){BlockingQueue<String> queue = new LinkedBlockingQueue<String>(5);  //定义一个容量为5的阻塞队列Consumer c = new Consumer(queue);Producer p = new Producer(queue);new Thread(p,"Producer"+(1)).start();   //初始化生产者线程new Thread(c,"Consumer"+(1)).start();   //初始化消费者线程}}

原创粉丝点击