package demo1;
import java.util.Objects;
public class Race implements Runnable{
private static String winner;//定义一个胜利者
@Override
public void run() {
for (int i = 0; i <= 10000; i++) {
//模拟兔子休息
if(Objects.equals(Thread.currentThread().getName(), "rabbit") && i%80==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()+" "+"run"+" "+i);
}
}
private boolean gameOver(int step){
if(winner!=null){
return true;
} else if (step == 10000) {//判断胜利者
winner = Thread.currentThread().getName();
System.out.println("winner is"+" "+winner);
return true;
}
return false;
}
public static void main(String[] args) {
Race race1 = new Race();//新建线程对象
//调用线程
new Thread(race1,"rabbit").start();
new Thread(race1,"tortoise").start();
}
}
标签:赛跑,int,龟兔,多线程,public,模拟
From: https://www.cnblogs.com/qt0312/p/16787868.html