package org.example;
public class Race implements Runnable {
//胜利者
private static String winner;
@Override
public void run() {
for(int i=0;i<=100;i++){
boolean flag =gameOver(i);
//如果flag>=100,结束比赛
if(flag){
break;
}
System.out.println(Thread.currentThread().getName()+"跑了"+i+"米");
}
}
//判断比赛是否结束
private boolean gameOver(int a){
if(winner!=null){
return true;
}{
if(a==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();
}
}
winner=Thread.currentThread().getName(); 获取进程的名字
如果兔子中途睡觉
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("兔子")&& i%5==0){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
boolean flag =gameOver(i);
if(flag){
break;
}
System.out.println(Thread.currentThread().getName()+"跑了"+i+"米");
}
}
private boolean gameOver(int a){
if(winner!=null){
return true;
}{
if(a==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();
}
}
其中i%5==0是定义兔子跑了多少步开始睡觉