java 解释一下这个怎么改才能出现正常点?
问题描述:
求帮助 解释一下这个怎么才能改 怎么优化? 求java代码。请问下这个java代码怎么写!thanks
答
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();//挑选全部
}
}
}
答
牛哇 方法里面声明方法
答
什么优化啊,你那是报错,()和{}中间多了个;
答
30行 分号去掉
答
整个类截图看下
答
public class _Exercise {
// 定义成员变量
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();//挑选全部
}
}
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 + "}";
}
}
}}