正在回答 回答被采纳积分+1
2回答
慕斯9009508
2017-11-09 22:27:18
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | 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积分~
来为老师/同学的回答评分吧