用java利用多线程技术模拟出龟兔赛跑的场面,设计一个线程类模拟参与赛跑的角色,创建该类的两个对象分别代表乌龟和兔子,兔子跑速快但在中间休息的睡眠时间长些。到终点线程运行结束
时间: 2024-03-02 18:54:22 浏览: 54
多线程演示龟兔赛跑
好的,以下是Java多线程模拟龟兔赛跑的代码示例:
```
public class Racing {
public static void main(String[] args) {
Thread turtle = new Thread(new Turtle(), "Turtle");
Thread rabbit = new Thread(new Rabbit(), "Rabbit");
turtle.start();
rabbit.start();
}
}
class Turtle implements Runnable {
private int totalDistance = 100;
private int step = 1;
@Override
public void run() {
while (totalDistance > 0) {
totalDistance -= step;
System.out.println(Thread.currentThread().getName() + " runs " + step + " steps, " + totalDistance + " steps left.");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + " wins!");
}
}
class Rabbit implements Runnable {
private int totalDistance = 100;
private int step = 2;
private int sleepTime = 200;
@Override
public void run() {
while (totalDistance > 0) {
totalDistance -= step;
System.out.println(Thread.currentThread().getName() + " runs " + step + " steps, " + totalDistance + " steps left.");
if (totalDistance <= 0) {
break;
}
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + " wins!");
}
}
```
上面的代码中,我们创建了两个线程类 `Turtle` 和 `Rabbit`,分别代表龟和兔子。在 `Turtle` 的 `run()` 方法中,我们循环计算龟走的步数,每次减去1,然后打印出走的步数和剩余步数,并通过 `Thread.sleep()` 方法使线程休眠100毫秒,模拟出龟走得比较慢的效果。在 `Rabbit` 的 `run()` 方法中,我们循环计算兔子走的步数,每次减去2,然后打印出走的步数和剩余步数,同时在中途通过 `Thread.sleep()` 方法使线程休眠200毫秒,模拟出兔子休息的效果。当有一个线程的 `totalDistance` 变量减到了或小于0时,就说明该线程到达了终点,我们就可以通过打印出该线程的名字来判断哪个角色赢得了比赛。
阅读全文