消费者生产者源代码Java实现

以厨师和服务生为例:

/**
 * 生产者与消费者问题
 */
public class Demo{
    public static void main(String[] args) {
        Food f = new Food();
        new cook(f).start();
        new waiter(f).start();
    }

}

/**
 * 厨师
 */
class cook extends Thread{
    private Food f;

    public cook(Food f){
        this.f = f;
    }
    @Override
    public void run() {
        for (int i = 0 ;i<100;i++){
            if (i%2==0){
                f.setNameAndTaste("老干妈","辣味");
            }else {
                f.setNameAndTaste("小米粥","甜味");
            }
        }

    }
}

/**
 * 服务生
 */
class waiter extends Thread{
    private Food f;
    public waiter(Food f){
        this.f = f;
    }
    @Override
    public void run() {

        for (int i = 0 ;i<100;i++) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            f.get();
        }
    }
}

/**
 * 菜名
 */
class Food{
    private String name;
    private String taste;
    private boolean flag = true;//标记是否可以生产

    public synchronized void setNameAndTaste(String name,String taste) {
        this.name = name;
        if (flag) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            this.taste = taste;
            flag = false;
            this.notifyAll();//唤醒在this下的所有睡着的线程
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public synchronized void get(){
        if (!flag) {
            System.out.println("菜名为:" + name + ",味道:" + taste);
            flag = true;
            this.notifyAll();
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

运行结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值