一、龟兔赛跑
1、赛道100米
2、乌龟与兔子一起跑步
3、要乌龟赢,兔子睡觉
二、乌龟是怎样获胜 的?
代码如下(示例):
public class run implments Runnable{
//定义获胜者
private static String winner;
//实现run方法
@Override
public void run(){
//打印兔子和乌龟的步数
for(int i=0;i<=100;i++){
//如果乌龟赢,兔子就要睡觉,假设兔子在50m处睡觉
if(i==50){
if(Thread.CurrentThead.getName()=="兔子"){
try{
//兔子睡一会吧
Thread.sleep(200)
}catch(Exception e){
e.printStackTrace();
}
}
}
System.out.println(Thread.CurrentThread.getName+"跑路”+i+"步“);
}
}
//定义游戏
public static boolean game(int steps){
//当没有获胜者时,继续跑路
if(winner!=null){
return false;
}
if(steps>=100){
winner=Thread.CurrentThead.getName();
System.out.println("winner is"+winner);
}
}
public static void main (Args[] args){
Run run=new Run();
new Thread(run,"兔子").start();
new Thread(run,"乌龟").start();
}
}
2.结局
结果如下(示例):
兔子-->跑路39步
兔子-->跑路40步
乌龟-->跑路32步
兔子-->跑路41步
乌龟-->跑路33步
.......
乌龟-->跑路98步
乌龟-->跑路99步
winnner is:乌龟
总结
乌龟与兔子本质就是两个小东西在一条道上跑,乌龟要赢,那就安排乌龟赢。
这两个小东西就像是两个线程使用同一资源,乌龟要用,就让兔子睡觉。