八、龟兔赛跑
案例:
- 首先来个赛道距离,然后要离终点越来越近
- 判断比赛是否结束
- 打印出胜利者
- 龟兔赛跑开始
- 故事中是乌龟赢的,兔子需要睡觉,所以我们来模拟兔子睡觉
- 终于,乌龟赢得比赛
代码:
public class Race implements Runnable{ final int nums=100; private static String winner; public static void main(String[] args) { Race race = new Race(); new Thread(race,兔子).start(); new Thread(race,乌龟).start(); } @Override public void run() { //模拟兔子睡觉 String name = Thread.currentThread().getName(); if (name.equals(兔子)){ try { Thread.sleep(2); } catch (InterruptedException e) { throw new RuntimeException(e); } } for (int i = 1; i <= nums; i++) { boolean gameOver = isGameOver(i); if (gameOver){ break; } System.out.println(name +跑到了+i); } } boolean isGameOver(int steps){ if (winner!=null){ return true; }else if (steps==nums){ winner=Thread.currentThread().getName(); System.out.println(winner+赢了); return true; }else return false; } }
结果: