请老师检查,谢谢老师!

来源:5-3 自由编程

weixin_慕码人9127363

2020-10-19 22:59:27

# 具体遇到的问题

# 报错信息的截图

# 相关课程内容截图

# 尝试过的解决思路和结果

# 粘贴全部相关代码,切记添加代码注释(请勿截图)

package com.zhong.weather;


public class Weather {

private int temperature;

private int himidity;

boolean flag=false;

public int getTemperature() {

return temperature;

}

public void setTemperature(int temperature) {

this.temperature = temperature;

}

public int getHimidity() {

return himidity;

}

public void setHimidity(int himidity) {

this.himidity = himidity;

}

@Override

public String toString() {

// TODO Auto-generated method stub

return "[温度:"+this.getTemperature()+",湿度:"+this.getHimidity()+"]";

}

public synchronized void generate(){//生产者

if(flag){

try {

wait();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

this.setHimidity((int)(Math.random()*100));

this.setTemperature((int)(Math.random()*40));

System.out.println("生成天气数据"+this);

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);

flag=false;

notifyAll();

}

}

package com.zhong.weather;


public class GenerateWeather implements Runnable {

Weather weather;

GenerateWeather(Weather weather){

this.weather=weather;

}

@Override

public void run() {

// TODO Auto-generated method stub

int i=1;

while(i<=100){

weather.generate();

try {

Thread.sleep(5000);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}


}

package com.zhong.weather;


public class ReadWeather implements Runnable {

Weather weather;

ReadWeather(Weather weather){

this.weather=weather;

}

@Override

public void run() {

// TODO Auto-generated method stub

int i=1;

while(i<=100){

weather.read();

try {

Thread.sleep(100);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}


}

package com.zhong.weather;


public class Test {


public static void main(String[] args) {

// TODO Auto-generated method stub

Weather weather=new Weather();

new Thread(new GenerateWeather(weather)).start();

new Thread(new ReadWeather(weather)).start();

}


}


写回答

1回答

好帮手慕小班

2020-10-20

同学你好,测试代码是正确的,完成的很棒!继续加油!祝学习愉快~

0

0 学习 · 16556 问题

查看课程