有个题还没解决,但觉得很重要。所以发上来求解答

XING1050192507 XING1050192507 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
题目要求:模拟妈妈做饭,做饭时发现没有盐了,让儿子去买盐(假设买盐需要3分钟),只有盐买回来之后,妈妈才能继续做饭的过程。

然后这是我写的:

//创建妈妈类
class Mother implements Runnable{
//设置初始盐量
static int SaltUsage=0;
//设置标志
boolean cooking =true;
@Override
public void run() {
// TODO Auto-generated method stub
while(cooking){
if(SaltUsage==0){ //发现盐不够
Son son=new Son(); //创建son的实例化对象
son.buySalt(); //用son的实例化对象条用son类内部的方法,较儿子去买盐
System.out.println("我将等你买盐");
waitForSon();
}
System.out.println("现在的盐量是 "+SaltUsage+" 足够半个月的饭菜用了");
System.out.println("继续做饭");
}

}
//等待儿子买盐回来
public synchronized void waitForSon(){
System.out.println("妈妈等儿子买盐回来");
try {
wait();
System.out.println("妈妈等儿子买盐回来");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//创建儿子类
class Son extends Thread{
//设置标记
boolean free = true;
@Override
public void run(){
while(free){
try {
sleep(180);
Mother.SaltUsage =100;
System.out.println("买了 "+Mother.SaltUsage+" 盐回来");
sonNotify(); //唤醒妈妈
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
free=false;
}
}
public synchronized void buySalt(){
Son son=new Son();
son.start();
}
public synchronized void sonNotify(){
notify();
}
}
public class Test10 {
public static void main(String[] args) {
Mother mother =new Mother();
new Thread(mother).start();
}
}


运行结果是:

我将等你买盐
妈妈等儿子买盐回来
买了 100 盐回来


也就是本程序没有运行起来阿,不知道哪里的问题。可能是同步锁的问题
...全文

相关推荐

评论 14
收藏 已收藏
分享
返回顶部
XING1050192507
Java EE 67,535 成员 225,843 内容