检查代码
来源:5-3 自由编程
慕少6083615
2022-03-22 16:26:22
package com.java.queue;
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((int)(Math.random()*41));
this.setHumidity((int)(Math.random()*101));
System.out.println("生成天气数据"+this.toString());
flag=true;
notifyAll();
}
public synchronized void read() {
if(!flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("读取天气数据"+this.toString());
flag=false;
notifyAll();
}
@Override
public String toString() {
return "[温度:"+this.getTemperature()+",湿度:"+this.getHumidity()+"]";
}
}package com.java.queue;
public class GenerateWeather implements Runnable{
Weather weather;
public GenerateWeather(Weather weather) {
this.weather=weather;
}
@Override
public void run() {
for(int i=1;i<=100;i++) {
weather.generate();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}package com.java.queue;
public class ReadWeather implements Runnable{
Weather weather;
public ReadWeather(Weather weather) {
this.weather=weather;
}
@Override
public void run() {
for(int i=1;i<=100;i++) {
weather.read();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}package com.java.queue;
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回答
同学你好,同学的代码符合题目要求,逻辑清晰,书写规范,做的很棒。
祝学习愉快~
相似问题