标签:
多生产者多消费者是Java中的一个经典的案例,采用等待唤醒机制来实现,代码如下:
public class ProducerConsumer { public static void main(String[] args) { Resource res=new Resource(); Producer pro1=new Producer(res); Producer pro2=new Producer(res); Consumer con1=new Consumer(res); Consumer con2=new Consumer(res); Thread t1=new Thread(pro1); Thread t2=new Thread(pro2); Thread t3=new Thread(con1); Thread t4=new Thread(con2); t1.start(); t2.start(); t3.start(); t4.start(); } } class Resource { private int count; private boolean flag=true; public synchronized void produce() { while(!flag) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName()+"生产"+count+"烤鸭"); count++; flag=false; this.notifyAll(); } public synchronized void consume() { while(flag) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName()+"消费"+count+"烤鸭"); flag=true; this.notifyAll(); } } class Producer implements Runnable{ Resource r; public Producer(Resource r) { super(); this.r = r; } @Override public void run() { while(true) { r.produce(); } } } class Consumer implements Runnable { Resource r; public Consumer(Resource r) { super(); this.r = r; } @Override public void run() { while(true) { r.consume(); } } }
还有一种采用BlockQueue实现的多生产者多消费者模式:
import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public class ProducerConsumer { public static void main(String[] args) { Resource res=new Resource(); BlockingQueue queue=new LinkedBlockingQueue(1); Producer pro1=new Producer(res,queue); Producer pro2=new Producer(res,queue); Consumer con1=new Consumer(res,queue); Consumer con2=new Consumer(res,queue); Thread t1=new Thread(pro1); Thread t2=new Thread(pro2); Thread t3=new Thread(con1); Thread t4=new Thread(con2); t1.start(); t2.start(); t3.start(); t4.start(); } } class Resource { int count; @Override public String toString() { return "Food [count=" + count + "]"; } } class Producer implements Runnable{ Resource r; BlockingQueue queue; public Producer(Resource r, BlockingQueue queue) { super(); this.r = r; this.queue = queue; } @Override public void run() { while(true) { produce(); } } public void produce() { try { System.out.println("生产"+r); queue.put(r); r.count++; } catch (InterruptedException e) { e.printStackTrace(); } } } class Consumer implements Runnable { Resource r; BlockingQueue queue; public Consumer(Resource r, BlockingQueue queue) { super(); this.r = r; this.queue = queue; } @Override public void run() { while(true) { consume(); } } public void consume() { try { System.out.println("消费"+queue.take()); } catch (InterruptedException e) { e.printStackTrace(); } } }
标签:
原文地址:http://www.cnblogs.com/hlhdidi/p/5629600.html