class ProductFactory { //定义库存最大 private int stock = 10; private LinkedList<String> products; public ProductFactory() { this.products = new LinkedList<>(); } public synchronized void productsStock(String product) throws InterruptedException { while (stock == products.size()) { System.out.println("警告:线程(" + Thread.currentThread().getName() + ")准备生产产品,但产品池已满"); wait(); } try { Thread.sleep(1000);//根据需求为了便于观察结果,每消费一个产品,sleep 1000 ms } catch (InterruptedException e) { e.printStackTrace(); } products.add(product); System.out.println("线程(" + Thread.currentThread().getName() + ")生产了一件产品,放在" + (Integer.valueOf(product)+1)+"商品位" + ";当前剩余商品" + products.size() + "个"); notify(); } /** * 消费方法 */ public synchronized void consumeStock() throws InterruptedException { while (products.size() == 0) { System.out.println("警告:线程(" + Thread.currentThread().getName() + ")准备消费产品,但当前没有产品"); wait(); } try { Thread.sleep(1000);//根据需求为了便于观察结果,每消费一个产品,sleep 1000 ms } catch (InterruptedException e) { e.printStackTrace(); } String product = products.remove(0); System.out.println("线程(" + Thread.currentThread().getName() + ")消费了一件"+(Integer.valueOf(product)+1)+"号商品位商品"+ ";当前剩余商品" + products.size() + "个"); notify(); } } class Producer implements Runnable { private ProductFactory factory; public Producer(ProductFactory factory) { this.factory = factory; } @Override public void run() { int i=0; try { while (true) { factory.productsStock(String.valueOf(i)); i++; } } catch (InterruptedException e) { e.printStackTrace(); } } } class Consume implements Runnable { private ProductFactory factory; public Consume(ProductFactory factory) { this.factory = factory; } @Override public void run() { try { while (true) { factory.consumeStock(); } } catch (InterruptedException e) { e.printStackTrace(); } } } public class DemoProduct { public static void main(String[] args) { ProductFactory productFactory = new ProductFactory(); new Thread(new Consume(productFactory),"1号消费者").start(); new Thread(new Consume(productFactory),"2号消费者").start(); new Thread(new Consume(productFactory),"3号消费者").start(); new Thread(new Producer(productFactory),"1号生产者").start(); new Thread(new Producer(productFactory),"2号生产者").start(); } }
标签:消费者,Thread,ProductFactory,生产者,factory,模式,products,new,public From: https://www.cnblogs.com/shaoyongwang/p/17275553.html