Java Monitor Object在生产者消费者问题中的应用

来源:互联网 发布:java开发人员岗位职责 编辑:程序博客网 时间:2024/06/06 08:43
直接上代码
package javaL.homework;import java.util.ArrayList;import java.util.List;/** * Producer and Consumer problem * @author yaolei * */public class ProducerAndConsumer {public static void main(String[] args) {PCMonitor monitor = new PCMonitor();//monitor objectThread p1 = new Thread(new Producer(1, monitor));Thread p2 = new Thread(new Producer(2, monitor));Thread p3 = new Thread(new Producer(3, monitor));Thread c1 = new Thread(new Consumer(1, monitor));Thread c2 = new Thread(new Consumer(2, monitor));Thread c3 = new Thread(new Consumer(3, monitor));//start threadsp1.start();p2.start();p3.start();c1.start();c2.start();c3.start();}}class Producer implements Runnable {private PCMonitor mtr = null;//the object which contains sharing resource private int producerNo; // the number of the Producerpublic Producer(int no, PCMonitor mtr) {this.mtr = mtr;this.producerNo = no;}@Overridepublic void run() {// TODO Auto-generated method stubint productNo = 0;while (true) {Product p = new Product(producerNo,productNo++);try {mtr.put(p);System.out.println("Producer " + producerNo + " is producing product[" + p + "]");Thread.sleep(1000);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}class Consumer implements Runnable {private PCMonitor mtr = null;private int consumerNo;public Consumer(int no, PCMonitor mtr) {this.mtr = mtr;this.consumerNo = no;}@Overridepublic void run() {// TODO Auto-generated method stubwhile (true) {try {Product p = mtr.get();System.out.println("Consumer " + consumerNo + " is consuming product[" + p + "]");Thread.sleep(1000);} catch (Exception e) {e.printStackTrace();}}}}class PCMonitor {private List<Product> items = new ArrayList<Product>();final static int MAX_COUNT = 20;//The max number of products in queuepublic synchronized void put(Product item) throws Exception {while (items.size()>=20)//while conditionwait();items.add(item);notifyAll();// notify();}public synchronized Product get() throws Exception {while (items.isEmpty()) //while conditionwait();Product item = items.remove(0);notifyAll();//notify()return item;}}class Product {private int id;private int producerId;public Product(int producerId,int id) {super();this.id = id;this.producerId = producerId;}public String toString() {return producerId+":"+id;}}

原创粉丝点击