- 首先来个赛道距离, 然后要离终点越来越近
- 判断比赛是否结束
- 打印出胜利者
- 龟兔赛跑开始
- 故事中是乌龟赢的, 兔子需要睡觉, 所以我们来模拟兔子睡觉
- 终于, 乌龟赢得比赛
package com.shu.thread;
public class Race implements Runnable {
public static boolean isGameOver = false;
@Override
public void run() {
String name = Thread.currentThread().getName();
for (int i = 0; i < 100; i++) {
if (!isGameOver) {
System.out.println(name + " has run " + i + " steps.");
}else {
break;
}
if(i == 30 && name == "Rabbit"){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (i == 99) {
isGameOver = true;
System.out.println(name + " wins!");
}
}
}
public static void main(String[] args) {
new Thread(new Race(), "Rabbit").start();
new Thread(new Race(), "Turtle").start();
}
}