Java线程通信,多线程并发数据错乱问题

线程通信问题
用 notifyall 和 wait 和锁 的方法 解决多线程并发数据错乱问题
模拟厨师做菜和服务员端菜情况:
public class rr {
    public static void main(String[] args) {
   Food food=new Food();
   new Cook(food).start();        //两个线程
   new Waiter(food).start();

    }
}
class Food{
    private String name;
    private String taste;
    private boolean flag=true;          
    public synchronized void set(String name,String taste){
        if(flag) {
            this.name = name;
            this.taste = taste;
            System.out.println("1厨师做好了菜;菜名:" + this.name + "味道:" + this.taste);
            flag=false;
        }
        this.notifyAll();           //此方法执行完成,唤醒其他线程     
        try {
            this.wait();            //此线程进入等待
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public synchronized void get() {
        if(!flag) {
            System.out.println("2端出做好的菜;菜名:" + this.name + "味道:" + this.taste);
            flag=true;
        }
        this.notifyAll();                    //此方法执行完成,唤醒其他线程 
        try {
            this.wait();                     //此线程进入等待
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


}
class Cook extends Thread{
    Food food;
    Cook(Food food){
        this.food=food;
    }
    public  void cook(){
      for(int i=0;i<50;i++){
          try {
              Thread.sleep(100);
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
          if(i%2==0){
              food.set("酸菜鱼","酸味");
          }else {
              food.set("糖醋排骨","甜味");
          }
      }
    }

    @Override
    public void run() {
        cook();
    }
}
class Waiter extends Thread{
    Food food;
    Waiter(Food food){
        this.food=food;
    }
    public void take(){
        for(int i=0;i<50;i++) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            food.get();
        }
    }

    @Override
    public void run() {
        take();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值