//模拟归途赛跑
public class Race implements Runnable {
//胜利者
private static String winner;
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
//模拟兔子休息
if ("兔子".equals(Thread.currentThread().getName()) && i==50){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//判断比赛是否结束
boolean flag = gameover(i);
//比赛结束
if (flag){
break;
}
System.out.println(Thread.currentThread().getName()+"跑了"+i+"步");
}
}
//判断是否完成比赛
public boolean gameover(int step){
//判断是否由胜利者
if (winner!=null){
return true;
}else{
if (step == 100){
winner = Thread.currentThread().getName();
System.out.println("Winner is "+winner);
return true;
}
}
return false;
}
public static void main(String[] args) {
Race race = new Race();
new Thread(race,"兔子").start();
new Thread(race,"乌龟").start();
}
}
版权声明:本文为weixin_45637920原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。