java编写程序计算"龟兔赛跑"的结果,龟兔赛跑的起点到终点的距离为800米,乌龟的速度为1米/1000毫秒,兔子的速度为1.2米/1000毫秒,等兔子跑到第600米时选择休息120000毫秒,请编写多线程程序计算龟兔赛跑的结果。
时间: 2024-09-15 17:13:58 浏览: 57
为了编写一个Java多线程程序来模拟龟兔赛跑,我们可以创建两个线程,分别代表乌龟和兔子。乌龟以恒定速度持续前进,而兔子在开始阶段快速跑并到达一定距离后休息。以下是简单的程序实现:
```java
public class龟兔赛跑 {
private static final int FINISH_LINE = 800;
private static final int TURTLE_SPEED = 1; // 每1000毫秒移动1米
private static final double RABBIT_SPEED = 1.2; // 每1000毫秒移动1.2米
private static final int REST_TIME = 120000; // 兔子休息时间 (毫秒)
public static void main(String[] args) throws InterruptedException {
Thread turtleThread = new Thread(() -> simulateTurtle());
Thread rabbitThread = new Thread(() -> simulateRabbit());
turtleThread.start();
rabbitThread.start();
// 等待兔子完成休息
rabbitThread.join(REST_TIME);
// 如果此时乌龟还未到达终点,继续让乌龟跑
if (!isTurtleFinished()) {
turtleThread.join();
}
System.out.println("比赛结果:乌龟 " + (isTurtleFinished() ? "赢了" : "输了") + ", 距离:" + (isTurtleFinished() ? FINISH_LINE : "未到达"));
}
private static boolean isTurtleFinished() {
return turtlesMoved >= FINISH_LINE;
}
private static void simulateTurtle() {
turtlesMoved = 0;
while (turtlesMoved < FINISH_LINE) {
try {
Thread.sleep(TURTLE_SPEED * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
turtlesMoved++;
}
}
private static void simulateRabbit() {
rabbitsMoved = 0;
for (int i = 0; i < 600; i++) {
rabbitsMoved += RABBIT_SPEED;
try {
Thread.sleep(RABBIT_SPEED * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Thread.sleep(REST_TIME); // 兔子休息
}
private static int turtlesMoved = 0;
private static int rabbitsMoved = 0;
}
```
在这个程序中,我们使用`Thread`类创建了两个线程,一个模拟乌龟的持续运动,另一个模拟兔子的加速奔跑和休息。当兔子休息完毕,我们检查乌龟是否已经到达终点。如果乌龟先达到,那么它赢得了比赛。
阅读全文