java运用多线程编写一个程序模拟龟兔赛跑,乌龟的速度为1米/1500毫秒,兔子的速度为5米/500毫秒,等兔子跑到第700米时选择休息10000毫秒,结果乌龟赢得了比赛。
时间: 2023-06-16 15:03:12 浏览: 184
java多线程案例-龟兔赛跑
以下是一个简单的实现:
```java
public class TurtleRabbitRace {
private static final int FINISH_LINE = 1000;
private static final int REST_DISTANCE = 700;
private static int turtlePosition = 0;
private static int rabbitPosition = 0;
private static boolean isRaceFinished = false;
public static void main(String[] args) {
Thread turtleThread = new Thread(new Turtle());
Thread rabbitThread = new Thread(new Rabbit());
turtleThread.start();
rabbitThread.start();
while (!isRaceFinished) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (turtlePosition > rabbitPosition) {
System.out.println("Turtle wins!");
} else {
System.out.println("Rabbit wins!");
}
}
private static class Turtle implements Runnable {
private static final int TURTLE_SPEED = 1;
private static final int TURTLE_SLEEP_TIME = 1500;
@Override
public void run() {
while (!isRaceFinished) {
turtlePosition += TURTLE_SPEED;
System.out.println("Turtle is at " + turtlePosition + " meter");
if (turtlePosition >= FINISH_LINE) {
isRaceFinished = true;
System.out.println("Turtle has finished the race!");
}
try {
Thread.sleep(TURTLE_SLEEP_TIME);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
private static class Rabbit implements Runnable {
private static final int RABBIT_SPEED = 5;
private static final int RABBIT_SLEEP_TIME = 500;
private static final int REST_TIME = 10000;
@Override
public void run() {
while (!isRaceFinished) {
if (rabbitPosition >= REST_DISTANCE) {
System.out.println("Rabbit is taking a rest for " + REST_TIME + " milliseconds");
try {
Thread.sleep(REST_TIME);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
rabbitPosition += RABBIT_SPEED;
System.out.println("Rabbit is at " + rabbitPosition + " meter");
if (rabbitPosition >= FINISH_LINE) {
isRaceFinished = true;
System.out.println("Rabbit has finished the race!");
}
try {
Thread.sleep(RABBIT_SLEEP_TIME);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
```
在这个程序中,我们定义了一个 `Turtle` 和一个 `Rabbit` 类,它们都实现了 `Runnable` 接口,用于在多线程中运行。在 `main` 方法中,我们创建了两个线程,并且启动它们。
在 `Turtle` 类中,我们定义了乌龟的速度和睡眠时间,并且在 `run` 方法中使用一个循环不断地更新乌龟的位置,直到比赛结束。
在 `Rabbit` 类中,我们定义了兔子的速度和睡眠时间,以及一个休息时间和距离。在 `run` 方法中,我们首先检查兔子是否需要休息,如果需要,就让兔子睡觉一段时间。然后,我们更新兔子的位置,直到比赛结束。
最后,在 `main` 方法中,我们使用一个循环等待比赛结束,然后根据乌龟和兔子的位置判断谁赢了比赛。
阅读全文