老师,检查作业,看一下有没有需要修改的

来源:5-3 自由编程

UUU加油

2022-05-17 15:27:48

public class Weather {
	private int temperature;//温度
	private int humidity;//湿度
	boolean flag=false;
	
	public Weather() {
		
	}
	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) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		  }
		temperature=(int) (Math.random()*41);
		this.setTemperature(temperature);
		humidity=(int)(Math.random()*101);
		this.setHumidity(humidity);
		System.out.println("生成天气数据:"+this.toString());
		flag=true;
		 notifyAll();
	}
  
//读取天气的方法
  public synchronized void read() {
	  if(!flag) {
		  try {
			wait();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	  }
	System.out.println("读取天气数据:"+this.toString());
	 flag=false;	
	 notifyAll();
  }	
  
  public String toString() {
		return "[温度:"+temperature+",湿度:"+humidity+"]";
	}
}
public class GenerateWeather implements Runnable {
	Weather weather;
	
	public GenerateWeather(Weather weather) {
		this.weather=weather;
	}

	@Override
	public void run() {
		for(int i=0;i<=100;i++)
		weather.generate();
        try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
public class ReadWeather implements Runnable {
	Weather weather;
	public ReadWeather(Weather weather) {
		this.weather=weather;
	}

	@Override
	public void run() {
		for(int i=0;i<=100;i++) {
		weather.read();
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
}
public class WeatherTest {

	public static void main(String[] args) {
		//创建Weather对象
		Weather we=new Weather();
		//实例化线程类并启动线程	
		new Thread(new GenerateWeather(we)).start();;
		new Thread(new ReadWeather(we)).start();;
		
		
		

	}

}


写回答

1回答

好帮手慕小脸

2022-05-17

同学你好,代码是正确的,完成的不错,继续加油!

祝学习愉快~

0

0 学习 · 9886 问题

查看课程