消费者和生产者的案例

该博客展示了如何使用Java编程实现经典的生产者消费者问题。通过一个Box类,定义了put()方法用于生产牛奶(放入牛奶)和get()方法用于消费牛奶(取出牛奶)。在BoxDemo主类中创建了生产者和消费者线程进行交互,模拟实际场景。
摘要由CSDN通过智能技术生成
//牛奶箱类用来实现生产者和消费者的交互
public class Box {
    private int milknum=0;//定义一个牛奶数量
    private boolean state=false;//定义奶箱状态true表示奶箱中有牛奶

    //定义一个put方法表示存放牛奶

    public synchronized void put(int milknum) {

        if(state){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.milknum=milknum;
        System.out.println("把第"+this.milknum+"瓶牛奶送入箱中");
        state=true;
        notifyAll();
    }

    //定义一个取走牛奶的方法
    public synchronized void  get()  {
        if (state) {
            System.out.println("用户把第" + this.milknum + "瓶牛奶取走了");
            state=false;
            notifyAll();
        }
        else{
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
public class BoxDemo {
    public static void main(String[] args) {
        Box b=new Box();
        Customer c=new Customer(b);
        Producer p=new Producer(b);
        Thread t1=new Thread(p);
        Thread t2=new Thread(c);
        t1.start();
        t2.start();

    }
}

public class Customer implements Runnable{
    private Box b;
    public Customer(Box b) {
        this.b=b;
    }

    @Override
    public void run() {
while (true){
    b.get();
}
    }
}
public class Producer implements Runnable{
    private Box b;
    public Producer(Box b) {
        this.b=b;
    }

    @Override
    public void run() {
        for(int i=1;i<=5;i++){
            b.put(i);
        }


    }
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值