仓库类
package org.dennist.thread.demo; /** * * StoreHouse.java * * @version : 1.1 * * @author : 苏若年 <a href="mailto:DennisIT@163.com">发送邮件</a> * * @since : 1.0 创建时间: 2013-2-25 上午08:55:33 * * TODO : 仓库 * */ public class StoreHouse { private int base = 0; private int top = 0; //仓库大小 private Product[] products = new Product[10]; /** * 生产产品 * @param product */ public synchronized void push(Product product){ if(top==products.length){ //如果仓库已满,等待消费 try { System.out.println("仓库已满,正在等待消费.."); wait(); }catch (InterruptedException e) { System.out.println("stop push product because other reasons"); } } //仓库未满,将生产的产品入库 products[top] = product; //库中产品数量+1 top++; } /** * 消费产品 * @return */ public synchronized Product pop() { Product product = null; while (top == base) { //仓库未空,不能消费 notify(); try { System.out.println("仓库已空,正等待生产..."); wait(); } catch (InterruptedException e) { System.out.println("stop push product because other reasons"); } } //仓库未空,等待消费 top--; product = products[top]; products[top] = null; return product; } } |
生产者类
package org.dennist.thread.demo; /** * * Producer.java * * @version : 1.1 * * @author : 苏若年 <a href="mailto:DennisIT@163.com">发送邮件</a> * * @since : 1.0 创建时间: 2013-2-25 上午08:53:16 * * TODO : 生产者 * */ public class Producer implements Runnable{ private String producerName ; private StoreHouse storeHouse ; public Producer(String producerName, StoreHouse storeHouse) { this.producerName = producerName; this.storeHouse = storeHouse; } public void setProducerName(String producerName) { this.producerName = producerName; } public String getProducerName() { return producerName; } @Override public void run() { execProcuct(); } private void execProcuct() { int i = 0; while(true){ i++; Product pro = new Product(i); storeHouse.push(pro); System.out.println(getProducerName() + " 生产了 " + pro); try { Thread.sleep(2000); } catch (InterruptedException e) { return; } } } } |