5-3编程练习
来源:5-3 自由编程
小乌兹cxy
2022-01-28 21:34:41
问题描述:
我的代码总是运行一两个就不往下运行了
相关截图:

相关代码:
public class WeatherTest {
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 flag = 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(flag){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.setTemperature(new Random().nextInt(40));
this.setHumidity(new Random().nextInt(100));
System.out.println("生成天气数据" + this.toString());
flag = true;
}
public synchronized void read(){
if(!flag){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("读取天气数据"+ this.toString());
flag = false;
notifyAll();
}
public String toString(){
return "[温度:" + this.getTemperature() + ",湿度:" + this.getHumidity() + "]";
}
}相关代码:
public class ReadWeather implements Runnable{
Weather weather;
ReadWeather(Weather weather){
this.weather = weather;
}
public void run(){
for (int i = 0; i < 100 ; i++)
{
weather.read();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
i++;
}
}
}相关代码:
public class GenerateWeather implements Runnable{
Weather weather;
GenerateWeather(Weather weather){
this.weather = weather;
}
public void run(){
for (int i = 0; i < 100 ; i++) {
weather.generate();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
i++;
}
}
}1回答
好帮手慕小蓝
2022-01-29
同学你好,同学提供的代码格式错乱,老师这里无法对代码进行格式化。请同学提供所有类的代码,并且按照以下方式以Java的格式提供,这样老师可以完整的复制同学的代码,确保不会出现偏差。
祝学习愉快~

相似问题