- package week8.day2;
- class AirData{
- private int temperature;//温度
-
- private int humidity;//湿度
-
- private int windSpeed;//风速
-
- AirData(){temperature=0;humidity=0;windSpeed=0;}
-
- public void setTemperature(int temperature) {
- this.temperature = temperature;
- }
-
- public void setHumidity(int humidity) {
- this.humidity = humidity;
- }
-
- public void setWindSpeed(int windSpeed) {
- this.windSpeed = windSpeed;
- }
-
- public int getTemperature() {
- return temperature;
- }
- public int getHumidity() {
- return humidity;
- }
-
- public int getWindSpeed() {
- return windSpeed;
- }
-
- @Override
- public String toString() {
- return "温度:"+ this.getTemperature()+",湿度:" + this.getHumidity()+",风速:"+ this.getWindSpeed();
- }
- }
-
- class TestingSensor extends Thread{
- static int getValue(){
- return (int)(Math.random()*100);
- }
- private AirData airData ;
- public TestingSensor (AirData airData){
- this.airData=airData;
- }
- public void run() {
- while(true){
- synchronized (airData){
- //产生三个数据
- airData.setTemperature(getValue());
- airData.setHumidity(getValue());
- airData.setWindSpeed(getValue());
- System.out.println("传感器测试到的数据是 "+ airData);
- airData.notify();
- }
- try {
- Thread.sleep(5000);
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- }
- }
- }
-
- class Computer extends Thread{
- private AirData airData ;
-
- public Computer (AirData airData){
- this.airData=airData;
- }
-
- public void run() {
- for(int i=1;i<=2;i++){
- synchronized (airData){
- System.out.println("计算机显示第"+i+"次读取: "+ airData);
- try {
-
- airData.wait();
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- }
- try {
- //获取三个数据,并显示
- sleep(100);
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- }
- System.out.println("计算机显示次数已经结束");
-
- }
- }
-
- public class Test {
- public static void main(String[] args) {
- AirData airData = new AirData();
-
- Thread t1 = new TestingSensor(airData);
- Thread t2 = new Computer(airData);
-
- t1.setDaemon(true);//设置为影子线程 目的,让所有前台线程结束时,t1也跟着结束。
- t1.start();
- t2.start();
-
- System.out.println(Thread.currentThread().getName()+" 线程负责开始 t1 t2 然后结束");
- System.out.println(Thread.currentThread().getName()+" 线程负责开始 t1 t2 然后结束");
- }
- }