请老师指正5-3的作业是否正确?还有什么需要改的地方?
来源:5-3 自由编程
床前明月光i
2022-01-19 23:35:43
package com.imooc.thread;
/**
* 天气类
* @author
*
*/
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 boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
//生成天气的方法
public synchronized void generate() {
if(!flag) {
this.setTemperature((int)(Math.random()*41));
this.setHumidity((int)(Math.random()*101));
System.out.println("生成天气数据"+this.toString());
flag = true;
}else {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
notifyAll();
}
//读取天气的方法
public synchronized void read() {
if(flag) {
System.out.println("读取天气数据" +this.toString());
flag = false;
}else{
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
notifyAll();
}
@Override
public String toString() {
return "[温度:"+this.getTemperature()+",湿度:"+this.getHumidity()+"]";
}
}
/**
* 生成天气线程类
* @author
*
*/
public class GenerateWeather implements Runnable {
Weather weather = null;
public GenerateWeather(Weather w) {
// TODO Auto-generated constructor stub
this.weather = w;
}
@Override
public void run() {
// TODO Auto-generated method stub
for(int i = 0;i<99;i++) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
weather.generate();
}
}
}
/**
* 获取天气线程类
* @author
*
*/
public class ReadWeather implements Runnable {
Weather weather = null;
public ReadWeather(Weather w) {
this.weather = w;
}
@Override
public void run() {
// TODO Auto-generated method stub
for(int i = 0;i<99;i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
weather.read();
}
}
}
/**
* 测试类
* @author
*
*/
public class WeatherTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Weather w = new Weather();
new Thread(new GenerateWeather(w)).start();
new Thread(new ReadWeather(w)).start();
}
}2回答
好帮手慕小明
2022-01-20
同学您好,
同学的代码是正确的,望继续加油努力
祝同学学习愉快~
好帮手慕小蓝
2022-01-20
同学你好,同学的代码符合题目要求,逻辑清晰,书写规范,做的很棒。
祝学习愉快~
相似问题