5-3作业
来源:6-1 多线程总结
渡鸦12345
2017-09-29 23:06:30
为什么要重写toString()方法,而且toString()方法重写时候的条件判定为什么有问题呢?
package com.homework;
public class Weather {
private int temperature;
private int humidity;
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;
}
boolean flag = false;
public synchronized void generate() {
if (flag) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.setTemperature((int) (Math.random() * 40) + 1);
this.setHumidity((int) (Math.random() * 100) + 1);
System.out.println("生产天气数据 [温度:" + this.getTemperature() + ",湿度" + this.getHumidity() + "]");
flag = true;
notifyAll();
}
public synchronized void read() {
if (!flag) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.getHumidity();
this.getTemperature();
System.out.println("读取天气数据 [温度:" + this.getTemperature() + ",湿度" + this.getHumidity() + "]");
flag = false;
notifyAll();
}
// @Override
// public String toString() {
// if (!flag) {
// return "生产天气数据 [温度:" + this.getTemperature() + ",湿度" + this.getHumidity() +
// "]";
// } else {
// return "读取天气数据 [温度:" + this.getTemperature() + ",湿度" + this.getHumidity() +
// "]";
// }
// }
}
package com.homework;
public class GenerateWeather implements Runnable {
Weather weather;
public GenerateWeather(Weather weather) {
this.weather = weather;
}
@Override
public void run() {
int i = 0;
while (i < 100 && true) {
weather.generate();
// System.out.println(weather.toString()+i);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
i++;
}
}
}
package com.homework;
public class ReadWeather implements Runnable {
Weather weather;
public ReadWeather(Weather weather) {
this.weather = weather;
}
@Override
public void run() {
// TODO Auto-generated method stub
int i = 0;
while (i < 100 && true) {
weather.read();
// System.out.println(weather.toString());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
i++;
}
}
}
package com.homework;
public class WeatherTest {
public static void main(String[] args) {
// TODO Auto-generated mthod stub
Weather weather = new Weather();
new Thread(new GenerateWeather(weather)).start();
new Thread(new ReadWeather(weather)).start();
}
}
1回答
irista23
2017-09-30
generate()和read()都使用了天气的输出语句,两次或以上使用的代码封装成方法,提高代码的维护性性和扩展性。以后如果需求有更改输出信息要增加,可以只修改toString()方法。generate() 中flag为false的时候才生成,当有数据时为true时等待,read() 中当flag为false,也就是没有生成新的天气数据时,则等待。你说的判断条件有问题,是什么问题?另外,为了避免toString()方法中的判断,也可以在toString()方法中只return "天气 [温度:" + temperature + ", 湿度" + humidity + "]";生成和读取可以在generate() 和read()方法中。