编写java程序计算"龟兔赛跑"的结果,龟兔赛跑的起点到终点的距离为800米,乌龟的速度为1米/1000毫秒,兔子的速度为1.2米/1000毫秒,等兔子跑到第600米时选择休息120000毫秒,请编写多线程程序计算龟兔赛跑的结果。
时间: 2024-09-18 15:19:09 浏览: 43
java多线程龟兔赛跑程序.zip
在Java中,我们可以利用多线程来模拟龟兔赛跑的情景。首先,我们需要创建两个线程,分别代表乌龟和兔子。乌龟始终保持匀速前进,而兔子则先快速跑到一定距离后休息。以下是简单的代码实现:
```java
public class Race {
private static final int ENDPOINT = 800; // 起点到终点的距离
private static final long REST_TIME_MS = 120000; // 兔子休息时间(毫秒)
private static final double TURTLE_SPEED_MPS = 0.001; // 乌龟速度 (m/s)
private static final double RABBIT_SPEED_MPS = 0.012; // 兔子速度 (m/s)
public static void main(String[] args) throws InterruptedException {
Thread turtleThread = new Thread(() -> {
while (true) {
int distanceCovered = (int)(TURTLE_SPEED_MPS * 1000); // 计算乌龟每步的距离
if (distanceCovered >= ENDPOINT) {
System.out.println("乌龟到达终点,总耗时:" + getElapsedTime());
break;
}
System.out.println("乌龟前进到 " + distanceCovered + " 米");
}
});
Thread rabbitThread = new Thread(() -> {
for (int i = 0; i < 600; i += 1000) { // 兔子先跑600米
System.out.println("兔子跑到了 " + i + " 米");
if (i == ENDPOINT) {
break;
}
Thread.sleep(1000);
}
// 兔子休息
try {
Thread.sleep(REST_TIME_MS);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 然后继续跑余下的路程
while (rabbitPosition < ENDPOINT) {
// 假设兔子的速度在休息后不会恢复到最大值,简化处理
int distanceCoveredRabbit = (int)(RABBIT_SPEED_MPS * 1000);
rabbitPosition += distanceCoveredRabbit;
System.out.println("兔子跑到了 " + rabbitPosition + " 米");
if (rabbitPosition >= ENDPOINT) {
System.out.println("兔子也到达终点,总耗时:" + getElapsedTime());
break;
}
}
});
// 启动线程并等待它们完成
turtleThread.start();
rabbitThread.start();
turtleThread.join();
rabbitThread.join();
}
private static long getElapsedTime() {
return System.currentTimeMillis();
}
private static int rabbitPosition = 0;
}
```
阅读全文