package JavaSE.Thread.document01;
/**
* 模拟龟兔赛跑
*/
public class Demo05 implements Runnable {
public static String winner;//胜者
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
if (Thread.currentThread().getName().equals("兔子")&&i%20==0){
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//判断比赛是否结束
boolean winners = gameover(i);
if (winners){
break;
}
System.out.println(Thread.currentThread().getName() + "跑了" + i + "步");
}
}
private boolean gameover(int stepcount) {//判断是否完成比赛
if (winner != null) {//已经存在胜者
return true;
}
{
if (stepcount>=100){
winner=Thread.currentThread().getName();
System.out.println("胜者:"+winner);
return true;
}
}
return false;
}
public static void main(String[] args) {
Demo05 demo05 = new Demo05();
new Thread(demo05, "兔子").start();
new Thread(demo05, "乌龟").start();
}
}