Java实现龟兔赛跑,乌龟速度为100米每1000毫秒,兔子速度为100米每500毫秒,兔子跑到700米休息了1000毫秒,结果乌龟先跑完赢得比赛用多线程实现
时间: 2024-03-27 15:35:11 浏览: 130
Java多线程之龟兔赛跑
好的,这里是使用多线程实现龟兔赛跑的Java代码:
```java
public class Race {
public static void main(String[] args) {
int totalDistance = 1000; // 比赛总路程为1000米
int turtleSpeed = 100; // 乌龟速度为100米每1000毫秒
int rabbitSpeed = 100; // 兔子速度为100米每500毫秒
int rabbitSleepTime = 1000; // 兔子跑到700米后休息1000毫秒
int rabbitRestDistance = 700; // 兔子跑到700米后需要休息
// 创建乌龟和兔子两个线程
Thread turtle = new Thread(new Runner("乌龟", turtleSpeed, totalDistance));
Thread rabbit = new Thread(new Rabbit("兔子", rabbitSpeed, rabbitSleepTime, rabbitRestDistance, totalDistance));
// 启动两个线程
turtle.start();
rabbit.start();
}
}
// 参赛者类
class Runner implements Runnable {
private String name;
private int speed;
private int distance;
public Runner(String name, int speed, int distance) {
this.name = name;
this.speed = speed;
this.distance = distance;
}
@Override
public void run() {
int position = 0;
while (position < distance) {
// 参赛者前进
position += speed;
System.out.println(name + "跑了" + position + "米");
try {
Thread.sleep(1000); // 每次前进后休息1秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(name + "跑完了比赛!");
}
}
// 兔子类,继承自参赛者类
class Rabbit extends Runner {
private int sleepTime;
private int restDistance;
public Rabbit(String name, int speed, int sleepTime, int restDistance, int distance) {
super(name, speed, distance);
this.sleepTime = sleepTime;
this.restDistance = restDistance;
}
@Override
public void run() {
int position = 0;
while (position < super.distance) {
// 兔子前进
if (position < restDistance) {
position += super.speed;
} else {
System.out.println(super.name + "休息中...");
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
position += super.speed;
}
System.out.println(super.name + "跑了" + position + "米");
try {
Thread.sleep(500); // 每次前进后休息0.5秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(super.name + "跑完了比赛!");
}
}
```
这里我们创建了两个线程,分别代表乌龟和兔子参赛者。在参赛者类中,我们使用了一个 while 循环,每次循环参赛者都会往前跑一段距离并休息1秒。在兔子类中,我们重写了 run() 方法,在兔子前进时判断是否需要休息,并在需要休息时休息1000毫秒。在每次前进后,参赛者都会休息一段时间,以模拟现实中的参赛者跑步过程。
阅读全文