问题描述
/** * 经典生产者与消费者问题 * 生产者不断的往仓库中存放产品,消费者从仓库中消费产品。 * 其中生产者和消费者都可以有若干个。 * 仓库规则:容量有限,库满时不能存放,库空时不能取产品 。 */
产品
package product; /** * 商品 */ public class Product { private int id; private String name; public Product(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Product{" + "id=" + id + ", name='" + name + '\'' + '}'; } }
生产者
package product; import java.util.Random; public class Producter implements Runnable{ private Storage storage; public Producter(Storage storage) { this.storage = storage; } @Override public void run() { int i = 0; Random r = new Random(); while(i<10){//一个生产者生产10个商品这个线程就结束了 i++; storage.push(i,""+r.nextInt(10)); } } }
消费者
package product; /** * 消费者 */ public class Consumer implements Runnable{ private Storage storage = new Storage(); public Consumer(Storage storage) { this.storage = storage; } @Override public void run() { int i=0; while(i<10){//一个消费者消费10个商品这个线程就结束了 i++; storage.pop(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
仓库
package product; public class Storage { private Product[] products = new Product [10];//假设仓库只能容纳10个商品 private int top = 0; /** * 商品入库 */ public synchronized void push(int id,String name){ while(10==top){ try { System.out.println("Producter wait"); wait(); //仓库的商品满了,等待 } catch (InterruptedException e) { e.printStackTrace(); } } products[top] = new Product(id,name); System.out.println(Thread.currentThread().getName()+"生产了商品"+name); top++; System.out.println("Producter notifyAll"); notifyAll();//唤醒等待线程 } /** * 商品出库 */ public synchronized void pop(){ //仓库没商品 while(top==0){ try { System.out.println("Consumer wait"); wait();//仓库的商品为空,等待 } catch (InterruptedException e) { e.printStackTrace(); } } top--; Product product = new Product(products[top].getId(),products[top].getName()); products[top]=null; System.out.println(Thread.currentThread().getName()+"消费了产品"+product); System.out.println("Consumer notifyAll"); notifyAll();//唤醒等待线程 } }
测试
package product; public class ProductTest { public static void main(String[] args) throws InterruptedException { //只有1个仓库 Storage storage = new Storage(); //消费者线程 Consumer c1 = new Consumer(storage); Consumer c2 = new Consumer(storage); //生产者线程 Producter p1 = new Producter(storage); Producter p2 = new Producter(storage); new Thread(p1,"生产者1").start(); new Thread(p2,"生产者2").start(); Thread.sleep(1000); new Thread(c1,"消费者1").start(); new Thread(c2,"消费者2").start(); } }
结果
来源:https://www.cnblogs.com/cstdio1/p/12240800.html