请老师检查代码
来源:5-3 自由编程
王小east
2022-04-11 23:28:24
package com.imooc.weather;
public class Weather {
private int temperature;
private int humidity;
boolean flag = false;
public synchronized void setWeather(int temperature , int humidity) {
if(flag == true) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.temperature = temperature;
this.humidity = humidity;
System.out.println("生成天气数据[温度:" + this.temperature + "湿度:" + this.humidity + "]");
flag = true;
notifyAll();
}
public synchronized void getWeather() {
if(flag == false) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("读取天气数据[温度:" + this.temperature + "湿度:" + this.humidity + "]");
flag = false;
notifyAll();
}
}package com.imooc.weather;
public class Generate implements Runnable {
Weather weather;
public Generate(Weather weather) {
this.weather = weather;
}
@Override
public void run() {
// TODO Auto-generated method stub
int i =1;
while(i<=100) {
int t = (int)(Math.random()*40);
int h = (int)(Math.random()*100);
weather.setWeather(t, h);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
i++;
}
}
}package com.imooc.weather;
public class Read implements Runnable{
Weather weather;
public Read(Weather weather) {
this.weather = weather;
}
@Override
public void run() {
// TODO Auto-generated method stub
int i = 1;
while(i<=100) {
weather.getWeather();
i++;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}package com.imooc.weather;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Weather weather = new Weather();
Generate g = new Generate(weather);
Read r = new Read(weather);
Thread t1 = new Thread(g);
Thread t2 = new Thread(r);
t1.start();
t2.start();
}
}1回答
好帮手慕小脸
2022-04-12
同学你好,同学的代码符合题目要求,逻辑清晰,书写规范,做的很棒。
祝学习愉快~
相似问题