老是帮忙看一下代码有无问题
package cn.cdb.demo07;
import java.util.Random;
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();
}
}
Random random = new Random();
this.setTemperature(random.nextInt(40));
this.setHumidity(random.nextInt(100));
System.out.println("生成天气数据" + this.toString());
flag = true;
notifyAll();
}
public synchronized void read(){
if(!flag){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("读取天气数据" + this.toString());
flag = false;
notifyAll();
}
@Override
public String toString() {
return "[" + "温度:" + this.getTemperature() + ",湿度:" + this.getHumidity() + "]";
}
}package cn.cdb.demo07;
public class GenerateWeather implements Runnable {
Weather weather;
int n = 1;
public GenerateWeather(Weather weather2){
this.weather = weather2;
}
@Override
public void run() {
while(true){
weather.generate();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
n++;
if(n==100){
break;
}
}
}
}package cn.cdb.demo07;
public class ReadWeather implements Runnable {
Weather weather;
int n = 1;
public ReadWeather(Weather weather) {
this.weather = weather;
}
@Override
public void run() {
while (true) {
this.weather.read();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
n++;
if (n == 100) {
break;
}
}
}
}package cn.cdb.demo07;
public class WeatherTest {
public static void main(String[] args) {
Weather weather = new Weather();
new Thread(new GenerateWeather(weather)).start();
new Thread(new ReadWeather(weather)).start();
}
}0
收起
正在回答
1回答
练习完成的不错,加油,祝学习愉快~
Java零基础入门18
- 参与学习 人
- 提交作业 7317 份
- 解答问题 14452 个
想要入门学编程?多年一直活跃在编程语言排行版前列的Java是一个很好的选择。本路径将从Java基础语法、面向对象、常用工具类三部分,为你开启软件开发的大门!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星