Java并发协作——生产者、消费者模型
概述
示例
public class Concurrence { public static void main(String[] args) { WareHouse wareHouse = new WareHouse(); Producer producer = new Producer(wareHouse); Consumer consumer = new Consumer(wareHouse); new Thread(producer).start(); new Thread(consumer).start(); } } class WareHouse { private static final int STORE_SIZE = 10; private String[] storeProducts = new String[STORE_SIZE]; private int index = 0; public void pushProduct(String product) { synchronized (this) { while (index == STORE_SIZE) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } storeProducts[index++] = product; this.notify(); System.out.println("生产了: " + product + " , 目前仓库里共: " + index + " 个货物"); } } public synchronized String getProduct() { synchronized (this) { while (index == 0) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } String product = storeProducts[index - 1]; index--; System.out.println("消费了: " + product + ", 目前仓库里共: " + index + " 个货物"); this.notify(); return product; } } } class Producer implements Runnable { WareHouse wareHouse; public Producer(WareHouse wh) { this.wareHouse = wh; } @Override public void run() { for (int i = 0; i < 40; i++) { String product = "product" + i; this.wareHouse.pushProduct(product); } } } class Consumer implements Runnable { WareHouse wareHouse; public Consumer(WareHouse wh) { this.wareHouse = wh; } @Override public void run() { for (int i = 0; i < 40; i++) { this.wareHouse.getProduct(); } } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。