package com.Java;标签:赛跑,龟兔,return,currentThread,Thread,winner,多线程,public From: https://www.cnblogs.com/fc666/p/17145670.html
public class Race implements Runnable{
// 胜利者
private static String winner;
@Override
public void run() {
for (int i = 0; i <=100; i++) {
//如果是兔子就放慢速度
if (Thread.currentThread().getName().equals("兔子")){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
boolean lag = gameOver(i);
if(lag){
break;
}
System.out.println(Thread.currentThread().getName()+"-->跑了"+i+"米");
}
}
// 判断比赛是否完成
public boolean gameOver(int steps){
if(winner!=null){//已经有胜利者了
return true;
}
//当有人跑到100米时 比赛完成
if (steps>=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();
}
}