老师,为什么我的有错误

来源:5-3 自由编程

阿硕A

2020-01-21 20:41:52

package com.imooc.tongxun;

public class GenerateWeather implements Runnable {

	private Weather weather;
	public GenerateWeather() {
		
	}
	
	public GenerateWeather(Weather weather) {
		super();
		this.weather = weather;
	}

	
	@Override
	public void run() {
		// TODO Auto-generated method stub

		for(int i=1;i<101;i++) {
			weather.generate();
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}



}
package com.imooc.tongxun;

public class ReadWeather implements Runnable {

	private Weather weather;
	public ReadWeather() {
		
	}
	
	public ReadWeather(Weather weather) {
		super();
		this.weather = weather;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub

		for(int i=1;i<101;i++) {
			weather.read();
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}


}
package com.imooc.tongxun;

public class Weather {

	private int temperature;
	private int humidity;
	boolean flag=false;
	public Weather() {
		
	}
	public Weather(int temperature, int humidity) {
		super();
		this.temperature = temperature;
		this.humidity = 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;
	}
	public void generate() {
		if(flag) {
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		this.setTemperature((int)(Math.random()*40));
		this.setHumidity((int)(Math.random()*100));
		flag=true;
		notifyAll();
		System.out.println("生成天气数据"+toString());
		
	}
	public void read() {
		if(!flag) {
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		flag=false;
		notifyAll();
		System.out.println("读取天气数据"+toString());
	}
	public String toString() {
		return " [温度:" + this.getTemperature() + ", 湿度:" + this.getHumidity() + "]";
	}
}
package com.imooc.tongxun;

public class WeatherTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Weather wt1=new Weather();
		new Thread(new GenerateWeather(wt1)).start();;
		new Thread(new ReadWeather(wt1)).start();;
		
	}

}


写回答

1回答

好帮手慕小尤

2020-01-22

同学你好,是在调用wait()或者notify()之前,需要使用synchronized语义绑定住被wait/notify的对象。修改后代码如下:

http://img.mukewang.com/climg/5e27b0e1094afd9406250259.jpg

http://img.mukewang.com/climg/5e27b0f009fba22105380246.jpg

如果我的回答解决了你的疑惑,请采纳!祝学习愉快!

0

0 学习 · 11489 问题

查看课程