老师请检查下5-3作业,另外还有个问题在最下面请看下的

来源:5-3 自由编程

吹吹风泡泡茶

2022-02-06 22:10:49

package 多线程天气数据;


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 synchronized void generate() {

if(flag) {

try {

wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

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

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

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

flag=true;

notifyAll();

}

public synchronized void read() {

if(!flag) {

try {

wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

System.out.println("读取天气数据"+toString());

flag=false;

notifyAll();

}

public String toString() {

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

}

}



package 多线程天气数据;


public class GenerateWeather implements Runnable{

Weather weather;

public GenerateWeather(Weather weather) {

this.weather=weather;

}

@Override

public synchronized void run() {

for(int i=0;i<100;i++) {

weather.generate();

try {

Thread.sleep(5000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}


}



package 多线程天气数据;


public class ReadWeather implements Runnable{

Weather weather;

public ReadWeather(Weather weather) {

this.weather=weather;

}

@Override

public synchronized void run() {

for(int i=0;i<100;i++) {

weather.read();

try {

Thread.sleep(100);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}


}



package 多线程天气数据;


public class Test {


public static void main(String[] args) {

Weather weather=new Weather();

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

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

}


}


https://img.mukewang.com/climg/61ffd6650913924c09000796.jpg

https://img.mukewang.com/climg/61ffd67209a9b24d09000796.jpg


同步我是用在Weather里方法里了,但是另外两个线程类的run()方法里如果有多个代码比如这题,是否也要在run()方法上加上同步?我是加上了,请看下的

搜索

复制

写回答

1回答

好帮手慕阿园

2022-02-07

同学你好,代码完成的不错,很棒呐,继续加油!run()方法中不加synchronized也是可以的,同学可以去掉试试哦

另外不建议包名使用中文来命名哦

祝学习愉快~

1

0 学习 · 9886 问题

查看课程