java 利用wait() notifyAll()实现 生产者消费者模型

  • 运行时可能出现先消费在生产的情况,这是由于输出没跟上的结果,其内部运行结构是正确的。
  • 在进行等待时不要用if判断,而是要用while循环进行判断。
//测试生产者消费者模型
public class P_CTest {
    public static void main(String[] args) {
        BufferSpace bf=new BufferSpace();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(new Product_er("1号--生产者",bf)).start();
        new Thread(new Product_er("2号--生产者",bf)).start();
        new Thread(new Custom_er("1号--消费者",bf)).start();
        new Thread(new Custom_er("2号--消费者",bf)).start();
        //new Thread(new Custom_er("3号--消费者",bf)).start();
    }
}

/**
 * 生产者
 */
class Product_er implements Runnable{
    private String id;//生产者id,用于区分是哪个生产者
    BufferSpace bf;
    Product_er(String id,BufferSpace bf) {
        this.id = id;
        this.bf=bf;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 50; i++) {
            bf.sell(new Product(i));
            System.out.println(id+"生产了产品,ID-->"+i);
        }
    }
}

/**
 * 消费者
 */
class Custom_er implements Runnable{
    private String id;//消费者id,用于区分是哪个消费者
    private BufferSpace bf;
    Custom_er(String id,BufferSpace bf) {
        this.id = id;
        this.bf= bf;
    }

    @Override
    public void run() {
        for (int i = 0; i < 50; i++) {
            System.out.println(id+"消费了产品,ID-->"+bf.buy().getID());
        }
    }
}

/**
 * 产品
 */
class Product{
    private int ID;//产品id,用于区分是哪个产品
    Product(int id) {
        ID = id;
    }
    public int getID(){
        return ID;
    }
}

/**
 * 缓冲区,用于生产者于消费者交易产品的区域,有大小限制
 */
class BufferSpace{
    private int count=0;
    private Product[] pro =new Product[5];//缓冲区,放置已经生产完毕但没有被消费者取走的产品
    public synchronized void sell(Product p){
        while(count==5){
            try {
                System.out.println("货满了,正在等待消费者消费!");
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        pro[count++]=p;
        this.notifyAll();
        return;
    }
    public synchronized Product buy(){
        while (count==0){
            try {
                System.out.println("货没了,正在等待生产者生产!");
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        count--;
        this.notifyAll();
        return pro[count];
    }
}
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值