标签:
一、什么是生产者消费者模式?
生产者消费者模式是通过一个容器来解决生产者和消费者的强耦合问题。生产者和消费者彼此之间不直接通讯,而通过阻塞队列来进行通讯,所以生产者生产完数据之后不用等待消费者处理,直接扔给阻塞队列,消费者不找生产者要数据,而是直接从阻塞队列里取,阻塞队列就相当于一个缓冲区,平衡了生产者和消费者的处理能力。
二、为什么要使用生产者和消费者模式
在线程世界里,生产者就是生产数据的线程,消费者就是消费数据的线程。在多线程开发当中,如果生产者处理速度很快,而消费者处理速度很慢,那么生产者就必须等待消费者处理完,才能继续生产数据。同样的道理,如果消费者的处理能力大于生产者,那么消费者就必须等待生产者。为了解决这个问题于是引入了生产者和消费者模式。
三、代码实现:
public class Product { public int ID; public Product(int iD) { super(); ID = iD; } @Override public String toString() { return "ID=" + ID; } }
public class Factory { Product[] products = new Product[10]; int index = 0; public synchronized void push(Product p) { while (index == products.length) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.notify(); products[index] = p; index++; } public synchronized Product pop() { while (index == 0) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.notify(); index--; return products[index]; } }
public class Producer implements Runnable { Factory factory = null; public Producer(Factory factory) { super(); this.factory = factory; } @Override public void run() { for (int i = 0; i < 10; i++) { Product p = new Product(i); factory.push(p); System.out.println(Thread.currentThread().getName() + "生产了:" + p.toString()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
public class Consumer implements Runnable { Factory factory = null; public Consumer(Factory factory) { super(); this.factory = factory; } @Override public void run() { for (int i = 0; i < 10; i++) { Product p = factory.pop(); System.out.println(Thread.currentThread().getName() + "消费了:" + p.toString()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
public class Test { public static void main(String[] args) { Factory factory = new Factory(); Producer p1 = new Producer(factory); Consumer p2 = new Consumer(factory); new Thread(p1).start(); new Thread(p2).start(); } }
标签:
原文地址:http://www.cnblogs.com/chulei926/p/4701214.html