为了方便理解,自己敲了一边代码,记录 b站 狂神笔记。
//龟兔赛跑小案例
public class ThreadTest implements Runnable{
String winner;
@Override
public void run() {
for (int i = 0; i <=100; i++) {
//为了尊重历史,给兔子限制速度,每十步一假寐
if(Thread.currentThread().getName().equals("兔子")&& i%10==0){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
boolean flag=GameOver(i);
if (flag){
break;
}
System.out.println(Thread.currentThread().getName()+"跑了"+i+"步");
}
}
public static void main(String[] args) {
ThreadTest test=new ThreadTest();
new Thread(test,"兔子").start();
new Thread(test,"乌龟").start();
}
public boolean GameOver(int step){
if (winner!=null){
return true;
}
if (step==100)
{
winner=Thread.currentThread().getName();
System.out.println("winner is"+winner);
return true;
}
return false;
}
}
这这这…我电脑有点快,已经让兔子睡觉最低了,,这乌龟跑完了,还睡呢,,这乌龟本身就快。。。。



