创建两个对象,兔与龟,实现龟兔赛跑的过程 要求:兔子在跑到一半时睡觉,乌龟一直爬行,直到最后获得胜利。
时间: 2024-11-13 08:18:20 浏览: 18
龟兔赛跑PPT模板:智慧与速度的较量.pptx
在Java中,我们可以创建一个名为`Race`的类来模拟龟兔赛跑的过程,分别代表兔子和乌龟。这里有一个简化的示例:
```java
import java.util.concurrent.TimeUnit;
class Animal implements Runnable {
private String name;
private double speed;
public Animal(String name, double speed) {
this.name = name;
this.speed = speed;
}
@Override
public void run() {
while (!isVictory()) {
System.out.printf("%s is running at %.2f units per second.\n", name, speed);
try {
Thread.sleep(TimeUnit.SECONDS.toMillis(1));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(name + " wins the race!");
}
protected abstract boolean isVictory(); // 子类需实现此方法
}
class Rabbit extends Animal {
public Rabbit(double speed) {
super("Rabbit", speed);
}
@Override
protected boolean isVictory() {
return getDistanceCovered() >= 0.5; // 兔子达到终点半程即视为失败
}
private double getDistanceCovered() {
return speed * getRuntimeInSeconds();
}
private double getRuntimeInSeconds() {
return getThread().getStackTrace()[1].getLineNumber() / 2; // 模拟兔子跑了一半路程就睡了
}
}
class Turtle extends Animal {
public Turtle(double speed) {
super("Turtle", speed);
}
@Override
protected boolean isVictory() {
return true; // 因为乌龟一直在爬,只要比赛不停止,它总是赢家
}
}
public class Race {
public static void main(String[] args) {
Rabbit rabbit = new Rabbit(5); // 兔子速度较快
Turtle turtle = new Turtle(1); // 乌龟速度较慢
Thread rabbitThread = new Thread(rabbit);
Thread turtleThread = new Thread(turtle);
rabbitThread.start();
turtleThread.start();
try {
rabbitThread.join();
turtleThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
```
在这个示例中,`Animal`是抽象类,`Rabbit`和`Turtle`作为它的子类实现了`run()`方法。`Rabbit`会在运行到一定距离后暂停,而`Turtle`始终保持活动状态直至比赛结束。
阅读全文