java_关于生产者--消费者模式

生产者–消费者(–仓库)模式

此模式脱离仓库没有意义
(1)仓库用来存储数据
(2)仓库不满,生产
(3)仓库满足消费者要求时,消费
/**
 * 仓库类型
 */
public class Depot{
    private static final int MAX_NUM = 100;//仓库容量
    private int num;//库存
    public Depot(int num) {
        this.num = num;
    }
    /**消费方法*/
    public synchronized void consume(int need){
        while(need>num){
            try {
                this.wait();//供不应求,等待被通知
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("满足需求,可以购买"+need);
        num-=need;
        System.out.println("购买成功,仓库剩余:"+num);
        this.notifyAll();//主要通知生产者生产
    }
    /**生产方法*/
    public synchronized void product(int pro){
        while(pro+num>MAX_NUM){
            try {
                System.out.println("仓库空余位置不足,不能生产");
                this.wait();//供过于求,等待被通知
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("生产数量:"+pro);
        num+=pro;
        System.out.println("生产完毕,仓库剩余"+num);
        this.notifyAll();//主要通知消费者消费
    }
    public static void main(String[] args) {
        Depot depot = new Depot(30);
        Consumtor c1 = new Consumtor(depot, "小A", 40);
        Consumtor c2 = new Consumtor(depot, "小B", 50);
        Consumtor c3 = new Consumtor(depot, "小C", 60);
        Consumtor c4 = new Consumtor(depot, "小D", 45);

        Productor p1 = new Productor(depot, "x1", 30);
        Productor p2 = new Productor(depot, "x2", 50);
        Productor p3 = new Productor(depot, "x3", 70);
        Productor p4 = new Productor(depot, "x4", 40);
        Productor p5 = new Productor(depot, "x5", 60);

        c1.start();
        c2.start();
        c3.start();
        c4.start();

        p1.start();
        p2.start();
        p3.start();
        p4.start();
        p5.start();
    }
}
/**
 * 生产者
 * */
class Productor extends Thread{
    private Depot depot;//生产对象
    private String name;//生产者名称
    private int pro;//生产量
    public Productor(Depot depot, String name, int pro) {
        super();
        this.depot = depot;
        this.name = name;
        this.pro = pro;
    }
    public void run(){
        depot.product(pro);
    }
}
/**
 * 消费者
 * */
class Consumtor extends Thread{
    private Depot depot;//消费对象
    private String name;//消费者名称
    private int need;//消费需求量
    public Consumtor(Depot depot, String name, int need) {
        super();
        this.depot = depot;
        this.name = name;
        this.need = need;
    }
    public void run(){
        depot.consume(need);
    }
}

这里写图片描述

猜你喜欢

转载自blog.csdn.net/yc_hen/article/details/82312663