并发思想实现龟兔赛跑问题,龟兔相当于两个线性同时执行
//龟兔赛跑 并发问题
public class Race implements Runnable{
private static String winner;//定义获胜方,只有一名
@Override
public void run() {
//模拟赛道长100
for (int i = 0; i <= 200; i++) {
//模拟兔子休息,延时器
if(Thread.currentThread().getName().equals("兔子")&((i%10==0))){
//捕获异常
try {
Thread.sleep(1);//延时1毫秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//判断比赛是否结束
boolean game = gameOver(i);
//如果比赛结束就停止程序
if(game){
break;
}
System.out.println(Thread.currentThread().getName()+"跑了"+i+"步");
}
}
public static void main(String[] args) {
Race race = new Race();
new Thread(race,"乌龟").start();
new Thread(race,"兔子").start();
}
//判断比赛是否结束
private boolean gameOver(int steps){
//已经有获胜者了
if(winner!=null) {
return true;}
else {
if(steps>=200){
winner=Thread.currentThread().getName();
System.out.println(winner+"赢了比赛");
return true;
}
}
return false;
}
}
设置延时,兔子跑了16步时,乌龟已经跑完全程了赢得了比赛