正在回答 回答被采纳积分+1
2回答
慕斯9009508
2017-11-09 22:27:18
public class Weather {
private int temperature;
private int humidtiy;
boolean flag=false;
public int getTemperature() {
return temperature;
}
public void setTemperature(int temperature) {
this.temperature = temperature;
}
public int getHumidtiy() {
return humidtiy;
}
public void setHumidtiy(int humidtiy) {
this.humidtiy = humidtiy;
}
public synchronized void generate(int humodity,int temperature){
if(!flag){
System.out.println("生成数据"+this.toString());
this.setHumidtiy(humidtiy);
this.setTemperature(temperature);
flag=true;
}
}
public synchronized void read(){
if(flag){
System.out.println("读取数据"+this.toString());
flag=false;
}
}
@Override
public String toString() {
return "[温度=" + temperature + ", 湿度=" + humidtiy + "]";
}
}
import java.util.Random;
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++){
int s=(int)(Math.random())*30;
int t=(int)(Math.random())*40;
weather.generate(s,t);
try {
Thread.currentThread().sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Thread.currentThread().notifyAll();
}
}
}
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.currentThread().sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Thread.currentThread().notifyAll();
}
}
}
package com.java.weather;
public class Test {
public static void main(String[] args) {
Weather weather=new Weather();
GenerateWeather gweather=new GenerateWeather(weather);
ReadWeather rweather=new ReadWeather(weather);
new Thread(gweather).start();
new Thread(rweather).start();
}
}
Java零基础入门18
- 参与学习 人
- 提交作业 7317 份
- 解答问题 14452 个
想要入门学编程?多年一直活跃在编程语言排行版前列的Java是一个很好的选择。本路径将从Java基础语法、面向对象、常用工具类三部分,为你开启软件开发的大门!
了解课程



恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星