java多线程练习天气生成(5s)获取(0.1s)

本文介绍了使用Java进行多线程编程,实现每5秒生成一次天气信息,并确保在0.1秒内快速获取的实战案例。通过源代码解析,深入理解Java并发处理能力。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

 

 

 

 

 下面是源代码

package per.llldf.lx;

public class Weather {
	private int humidity;
	private int temperature;
	boolean flag = false;
	
	public Weather() {
		
	}
	
	public int getHumidity() {
		return humidity;
	}
	public void setHumidity(int humidity) {
		this.humidity = humidity;
	}
	public int getTemperature() {
		return temperature;
	}
	public void setTemperature(int temperature) {
		this.temperature = temperature;
	}
	@Override
	public String toString() {
		return " [湿度:" + humidity + ", 温度:" + temperature + "]";
	}
	
	public synchronized void get() {
		if (!flag) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}}
		System.out.println("获取的天气:" + this);
		flag = false;
		notifyAll();
	}
	public synchronized void gene() {
		if (flag) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}}
		this.setHumidity(((int)(Math.random() * 101)));
		this.setTemperature(((int)(Math.random() * 41)));
		System.out.println("生成的天气:" + this);
		flag = true;
		notifyAll();
	}
}
package per.llldf.lx;

public class Gene implements Runnable{
	Weather w;
	Gene(Weather w){
		this.w = w;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		for (int i = 0; i < 100; i++) {
		w.gene();
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}}
	
}
package per.llldf.lx;

public class Read implements Runnable{
	Weather w;
	Read(Weather w){
		this.w = w;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		for (int i = 0; i < 100; i++) {
		w.get();
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}}
	
}
package per.llldf.lx;

public class Test {
	public static void main(String[] args) {
		Weather w = new Weather();
		new Thread(new Gene(w)).start();
		new Thread(new Read(w)).start();
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

顺安晓迪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值