求帮助 解释一下这个怎么才能改 怎么优化? 求java代码。请问下这个java代码怎么写!thanks
7条回答 默认 最新
- m0_61487176 2021-10-28 11:24关注
public class asd { class Food { String name; int price; public Food(String name, int price) { this.name = name; this.price = price; } @Override public String toString() { return "Food{" + "name=" + name + "\"" + ", price=" + price + "}"; } } // 定义成员变量 Food food; // 定义2个同步方法 // 生产包子的方法 只有生产者执行 public synchronized void setFood(Food newFood) { // 判断蒸笼的状态 if (food == null) { //如果蒸笼为空 说明没有包子 //生产包子 food = newFood; System.out.println(Thread.currentThread().getName() + "生产了" + food); // 通知消费者来吃 notify //this.notify(); this.notifyAll(); } else { //如果蒸笼非空 说明有包子 //阻止自己放包子 wait try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } // 定义吃包子的方法 只有消费者执行 public synchronized void eatFood(){ // 判断蒸笼状态 if (food == null) { //如果蒸笼为空 说明没有包子 //阻止自己吃 wait try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } else { //如果蒸笼非空 说明有包子 System.out.println(Thread.currentThread().getName() + "吃了" + food); //吃包子 food=null; //通知生产者再生产 notify //this.notify this.notifyAll();//挑选全部 } } }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报