生产者消费者 多线程算法——用java编写的一个简单的小程序

不用多说,直接看代码O(∩_∩)O

package javaStudy; public class ConsumersAndProdusers { /** * 测试方法 * @param args */ public static void main(String[] args) { //建好数据仓库,并实例化 Storage storage = new Storage(); //建立消费者线程 Thread consumerThread = new Thread(new Consumers(storage)); consumerThread.setName("@消费线程@"); //建立生产者线程 Thread producerThread = new Thread(new Producers(storage)); producerThread.setName("@生产线程@"); //启动生产线程 和消费线程 consumerThread.start(); producerThread.start(); } } /** * 消费者类 * @author * */ class Consumers implements Runnable{ private Storage storage; public Consumers(Storage storage){ this.storage = storage; } public void run(){ while(true){ storage.pop(); } } } /** * 生产者类 * @author AB049399 * */ class Producers implements Runnable{ private Storage storage; public Producers(Storage storage){ this.storage = storage; } public void run() { Product product = new Product("@@产品id","产品名","产品其他信息"); while(true){ storage.push(product); } } } /** * 产品类 * @author AB049399 * */ class Product{ String id; String name; String others; public Product(String id,String name,String others){ this.id = id; this.name = name; this.others = others; } public String toString(){ return "( 产品id="+id+",产品名称="+name+",其他属性="+others+" )"; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getOthers() { return others; } public void setOthers(String others) { this.others = others; } } /** * 数据仓库类(做成栈的模式) * @author AB049399 * */ class Storage{ private final int STORAGE_SUM=10;//假设容量是10个 private Product[] products = new Product[STORAGE_SUM]; //产品仓库 private int top = 0;//当前仓库最上层一个 //生产产品 public synchronized void push(Product product){ while(top == STORAGE_SUM){//仓库容量已满,不能再生产,等待 try { System.out.println("当前仓库已满,线程"+Thread.currentThread().getName()+"等待中!"); wait(); } catch (InterruptedException e) { e.printStackTrace(); } } //把产品放入仓库 products[top++] = product; System.out.println(Thread.currentThread().getName()+"生产了新产品,产品信息:"+product.toString()); notifyAll();//唤醒所有等待线程 } //消费产品 public synchronized Product pop(){ while(top == 0){//仓库里的产品为空,等待 try { System.out.println("当前仓库没有产品,线程"+Thread.currentThread().getName()+"等待中!"); wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //消费产品 // Product product = products[--top]; Product product = new Product(products[--top].getId(),products[top].getName(),products[top].getOthers()); products[top] = null; System.out.println(Thread.currentThread().getName()+"消费了产品,产品信息:"+product.toString()); notifyAll();//唤醒所有等待线程 return product; } }

  

posted @ 2016-06-14 10:32  Into子房  阅读(396)  评论(0编辑  收藏  举报