代码运行为空白

来源:5-3 自由编程

养铲屎官的猫

2021-10-06 12:55:11

相关代码:

public class Test {
public static void main(String[] args) {
Weather weather = new Weather();
new Thread(new GenerateWeather(weather)).start();
new Thread(new ReadWeather(weather)).start();
}
}

相关代码:

public class Weather {
private int temperature;
private int humidity;相关代码:
boolean loop = false;

public int getTemperature() {
return temperature;
}

public void setTemperature(int temperature) {
this.temperature = temperature;
}

public int getHumidity() {
return humidity;
}

public void setHumidity(int humidity) {
this.humidity = humidity;
}

public synchronized void generate() {
if (!loop) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
temperature = (int) (Math.random() * 40);
humidity = (int) (Math.random() * 100);
System.out.println("生成天气数据" + toString());
loop = false;
notifyAll();
}
}

public synchronized void read() {
if (loop) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("读取天气数据" + toString());
loop = true;
notifyAll();
}
}

@Override
public String toString() {
return "温度:" + temperature +
", 湿度:" + humidity;
}
}

相关代码:

public class GenerateWeather implements Runnable {
Weather weather;

public GenerateWeather(Weather weather) {
this.weather = weather;
}

@Override
public void run() {
int i = 0;
while (i <= 100) {
i++;
weather.generate();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

相关代码:

public class ReadWeather implements Runnable {
Weather weather;

public ReadWeather(Weather weather) {
this.weather = weather;
}

@Override
public void run() {
int i = 0;
while (i <= 100) {
i++;
weather.read();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

代码加入中断和唤醒后运行就什么都不出现,不加入还能就能跑

写回答

1回答

好帮手慕小蓝

2021-10-06

同学你好,同学的代码有如下错误:

1.除去try...catch代码块外的所有代码,都应该在if结构之外。否则generate和read两个方法都会在wait之后无法被唤醒。修改位置如下图所示:

https://img.mukewang.com/climg/615d63370920dbe706970715.jpg

2.同学代码中generate和read两个方法的if判断条件和loop变化方式写反了。按照同学的代码运行结果可能会先进行读取,如下图所示:

https://img.mukewang.com/climg/615d633709a3089e09740883.jpg

修改方式如下图所示:

https://img.mukewang.com/climg/615d63370984fa7400000000.jpg

综上,同学的代码修改后如下图所示:

https://img.mukewang.com/climg/615d633809a72c5306280711.jpg

祝学习愉快~

0

0 学习 · 9886 问题

查看课程