龟兔赛跑问题
public class TestThread5 implements Runnable{
private static String winner;//注意final是静态常量不可修改
private static int num=0;
@Override
public void run() {
for (int i = 0; i <= 100000; i++) {
//模拟兔子休息
// if (Thread.currentThread().getName().equals("兔子") && i%10==0) {
// try {
// Thread.sleep(20);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
//判断比赛是否结束
boolean flag=gameOver(i);
if (flag) {
num=i;
break;
}
}
System.out.println(Thread.currentThread().getName()+"-->跑了"+num+"步");
}
private boolean gameOver(int steps){
if (winner != null) {
return true;
}else if (steps >=100000){
winner =Thread.currentThread().getName();
System.out.println("winner is "+winner);
return true;
}
return false;
}
public static void main(String[] args) {
TestThread5 testThread5=new TestThread5();
new Thread(testThread5,"兔子").start();
new Thread(testThread5,"乌龟").start();
}
}
实现结果
winner is 乌龟
兔子-->跑了35158步
乌龟-->跑了100000步