注意: 这里创建了一个方法来 判断比赛是否结束,胜利者是否出现,谁先到100步。
package com.yyf.Thread.demo1;
import com.sun.org.apache.bcel.internal.generic.NEW;
public class Race implements Runnable{
// static 代表只有唯一一个胜利者
private static String winner;
@Override
public void run() {
for (int i=0; i<=100;i++){
boolean flag = gameOver (i);
if (flag){
break;
}
System.out.println (Thread.currentThread ().getName ()+"==>跑了"+i+"步");
}
}
// 先定义一个是否比赛结束的方法
boolean gameOver(int step){
if (winner!=null){
System.out.println ("winner is "+ winner);
return true;
}
if (step>=100){
winner=Thread.currentThread ().getName ();
return true;
}
return false;
}
public static void main(String[] args) {
Race race = new Race ();
new Thread (race,"兔子").start ();
new Thread (race,"乌龟").start ();
}
}