生产者与消费者模式就是解耦生产者与消费者的模式,通过例如商品来建立他们之间的联系,生产者只要生产商品就行,消费者只要消费商品。常用于并发,生产者线程生产商品,消费者消费商品,通过消费信息进行通讯。
用object的wait与notify实现
//商品 public class Product { private int productTotal = 0; private int maxFruit = 10; public synchronized void produce() { if (productTotal == maxFruit) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.productTotal++; System.out.println(Thread.currentThread().getName() + "生产了一个商品,现仓储量:" + productTotal); this.notifyAll(); } public synchronized void consume() { if (productTotal == 0) { 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(); } } }