龟兔赛跑java多线程
时间: 2023-11-21 07:57:07 浏览: 93
以下是龟兔赛跑的Java多线程实现:
```java
public class Race {
public static void main(String[] args) {
RabbitAndTurtle rabbit = new RabbitAndTurtle("兔子", 2);
RabbitAndTurtle turtle = new RabbitAndTurtle("乌龟", 1);
rabbit.start();
turtle.start();
}
}
class RabbitAndTurtle extends Thread {
private String name;
private int speed;
private int distance = 0;
public RabbitAndTurtle(String name, int speed) {
this.name = name;
this.speed = speed;
}
@Override
public void run() {
while (distance < 100) {
double random = Math.random();
if (random < 0.3) {
distance += speed;
System.out.println(name + "跑了" + speed + "米,总共跑了" + distance + "米");
} else {
System.out.println(name + "睡觉了zzz");
}
}
System.out.println(name + "到达终点!");
}
}
```
阅读全文