生产者消费者模式

逻辑分析
1、生产者:生产产能品,通过一个生产标记,判断是否要生产产品
如果需要,则生产,并通知消费这消费
不需要则等待

2、消费者:消费产品,判断是否有足够的产品可以消费
可以消费的话,获取产品消费,并告知生产者
没有则等待

package productAndConsumer;

/**
 * 逻辑分析
 * 1、生产者:生产产能品,通过一个生产标记,判断是否要生产产品
 * 如果需要,则生产,并通知消费这消费
 * 不需要则等待
 *
 * 2、消费者:消费产品,判断是否有足够的产品可以消费
 * 可以消费的话,获取产品消费,并告知生产者
 * 没有则等待
 */
public class Program {
    public static void main(String[] args) {
        ProductPool pool=new ProductPool(20);
        new Productor(pool).start();
        new Consumer(pool).start();
    }
}

package productAndConsumer;

/**
 * 产品类
 */
public class Product {
    private String name;

    public Product(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

package productAndConsumer;

import java.util.LinkedList;
import java.util.List;

/**
 * 产品池
 * 统一管理产品
 * 生产者往池子里生产产品,消费者在池子里消费产品
 */
public class ProductPool {
    private List products;

    private int maxSize=0;

    public ProductPool(int maxSize) {
        this.products=new LinkedList();
        this.maxSize=maxSize;
    }

    /**
     * 生产者把生产的产品添加到商品池中
     * @param product
     */
     public synchronized void push(Product product){

         //判断产品是否充足
        while(this.products.size()==maxSize){
            try {
                this.wait();
                System.out.println("等待消费");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        this.products.add(product);
        //通知消费者来消费
        this.notifyAll();
     }

    /**
     * 消费者从产品池中取走一件产品
     * @return
     */
    public synchronized Product pop(){
        //判断产品池中是否还有产品可以消费
        while(this.products.size()==0){
            try {
                this.wait();
                System.out.println("等待生产");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Product product=this.products.remove(0);
        //通知生产者我消费了一件产品
        this.notifyAll();
        return  product;
    }

}

package productAndConsumer;

/**
 * 生产者类
 */
public class Productor extends Thread{

    private ProductPool pool;

    public Productor(ProductPool pool) {
        this.pool = pool;
    }

    @Override
    public void run() {
        for(int i=0;i<20;i++){

            String name=(int)(Math.random()*100)+"号产品";
            System.out.println("生产了一件产品"+name);
            Product product=new Product(name);
            this.pool.push(product);

        }
    }
}

package productAndConsumer;

public class Consumer extends Thread{

    private ProductPool pool;

    public Consumer(ProductPool pool) {
        this.pool = pool;
    }

    @Override
    public void run() {
        for(int i=0;i<20;i++){
            Product product=this.pool.pop();
            System.out.println("消费者消费了一件产品"+product.getName());
        }
    }
}

你可能感兴趣的:(java,多线程,设计模式,多线程)