packageexception.Demo03;//模拟龟兔赛跑,publicclassRaceimplementsRunnable{//胜利者privatestaticString winner;@Overridepublicvoidrun(){for(int i =0; i <=100; i++){//模拟兔子休息if(Thread.currentThread().getName().equals("兔子")&& i%10==0){try{Thread.sleep(10);}catch(InterruptedException e){thrownewRuntimeException(e);}}//判断是否完成比赛boolean flag =gameOver(i);if(flag){break;}System.out.println(Thread.currentThread().getName()+"--->跑了"+i+"步");}}privatebooleangameOver(int steps){//判断是否有胜利者if(winner!=null){//已经存在胜利者了returntrue;}{if(steps==100){
winner =Thread.currentThread().getName();System.out.println("winner is "+winner);returntrue;}}returnfalse;}publicstaticvoidmain(String[] args){Race race =newRace();newThread(race,"兔子").start();newThread(race,"乌龟").start();}}