请老师检查我的代码的正确和规范,谢谢
来源:5-3 自由编程
wangstudyvc
2020-06-26 14:55:24
public class Weather {
private int temperature;
private int humidity;
private boolean isReaded = true;
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 (!isReaded) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.setTemperature((int) (Math.random() * 41));
this.setHumidity((int) (Math.random() * 101));
System.out.println("生成天气数据" + this);
isReaded = false;
this.notifyAll();
}
public synchronized void read() {
if (isReaded) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("读取天气数据" + this);
isReaded = true;
this.notifyAll();
}
@Override
public String toString() {
return "[温度:" + this.getTemperature() + ",湿度:" + this.getHumidity() + "]";
}
}public class GenerateWeather implements Runnable {
private Weather weather;
public GenerateWeather(Weather weather) {
this.weather = weather;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.weather.generate();
}
}
}public class ReadWeather implements Runnable {
private Weather weather;
public ReadWeather(Weather weather) {
this.weather = weather;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.weather.read();
}
}
}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();
}
}1回答
同学你好
同学的代码写的不错哦,继续加油!!
祝学习愉快。
相似问题