java多线程实现体重跟踪,设计两个人类对象(一男一女),通过每天吃东西和运动。来计算他们生活一个月以后的体重
时间: 2024-02-18 15:06:27 浏览: 114
可以通过以下步骤来实现Java多线程体重跟踪:
1. 定义一个包含体重数据的类,例如WeightData。
```java
public class WeightData {
private double weight;
public void setWeight(double weight) {
this.weight = weight;
}
public double getWeight() {
return weight;
}
}
```
2. 创建一个继承Thread类的体重跟踪线程类,例如WeightTrackerThread。该线程类应该包含WeightData对象和人类对象作为属性。
```java
public class WeightTrackerThread extends Thread {
private final WeightData weightData;
private final Person person;
public WeightTrackerThread(WeightData weightData, Person person) {
this.weightData = weightData;
this.person = person;
}
@Override
public void run() {
for (int i = 0; i < 30; i++) { // 模拟一个月时间
double weight = weightData.getWeight();
weight += person.getWeightGain() - person.getWeightLoss(); // 计算每天的体重变化
weightData.setWeight(weight);
try {
Thread.sleep(24 * 60 * 60 * 1000); // 每天更新一次体重数据
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
```
3. 创建一个人类对象,例如Person。该对象包含每天的食物和运动信息,并提供获取体重变化的方法。
```java
public class Person {
private final String gender;
private final double weight;
private final double weightGain;
private final double weightLoss;
public Person(String gender, double weight, double weightGain, double weightLoss) {
this.gender = gender;
this.weight = weight;
this.weightGain = weightGain;
this.weightLoss = weightLoss;
}
public double getWeightGain() {
// 根据每天的饮食和运动计算体重增加
return weightGain;
}
public double getWeightLoss() {
// 根据每天的饮食和运动计算体重减少
return weightLoss;
}
}
```
4. 在主线程中,创建WeightData对象和两个Person对象,并启动两个WeightTrackerThread线程。
```java
public class Main {
public static void main(String[] args) {
WeightData weightData = new WeightData();
Person man = new Person("male", 70, 2500, 2000);
WeightTrackerThread manThread = new WeightTrackerThread(weightData, man);
manThread.start();
Person woman = new Person("female", 55, 2000, 1500);
WeightTrackerThread womanThread = new WeightTrackerThread(weightData, woman);
womanThread.start();
try {
manThread.join();
womanThread.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Man's weight after 1 month: " + man.getWeightGain() - man.getWeightLoss());
System.out.println("Woman's weight after 1 month: " + woman.getWeightGain() - woman.getWeightLoss());
System.out.println("Weight data after 1 month: " + weightData.getWeight());
}
}
```
在这个例子中,我们创建了一男一女两个人类对象,模拟了每天的食物和运动情况,并通过WeightTrackerThread线程来更新体重数据。最后在主线程中输出了每个人和整个月的体重数据。注意,由于男女的体重增加和减少可能不同,所以他们的最终体重也会不同。
阅读全文