生产者与消费者模式
Posted 柳无情
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了生产者与消费者模式相关的知识,希望对你有一定的参考价值。
生产者与消费者模式就是解耦生产者与消费者的模式,通过例如商品来建立他们之间的联系,生产者只要生产商品就行,消费者只要消费商品。常用于并发,生产者线程生产商品,消费者消费商品,通过消费信息进行通讯。
用object的wait与notify实现
//商品 public class Product { private int productTotal = 0; private int maxFruit = 10; public synchronized void produce() { this.productTotal++; if (productTotal > 0) { this.notifyAll(); System.out.println(Thread.currentThread().getName() + "生产了一个商品,现仓储量:" + productTotal); } if (maxFruit == 10) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } public synchronized void consume() { if (productTotal == 0) { if (productTotal <= maxFruit) { this.notifyAll(); } try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } else { this.productTotal--; System.out.println(Thread.currentThread().getName() + "消费了一个商品,现仓储量:" + productTotal); } } } //生产者 public class Producer implements Runnable { private Product fruitShop; public Producer(Product fruitShop) { this.fruitShop = fruitShop; } @Override public void run() { while (true) { fruitShop.produce(); } } } //消费者 public class Consumer implements Runnable { private Product fruitShop; public Consumer(Product fruitShop) { this.fruitShop = fruitShop; } @Override public void run() { while (true) { fruitShop.consume(); } } } public class TestLock5 { public static void main(String[] args) { Product fruitShop = new Product(); Producer producer = new Producer(fruitShop); Consumer consumer = new Consumer(fruitShop); Thread thread1 = new Thread(producer, "生产者"); Thread thread2 = new Thread(consumer, "消费者"); thread1.start(); thread2.start(); try { thread2.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
以上是关于生产者与消费者模式的主要内容,如果未能解决你的问题,请参考以下文章