其他分享
首页 > 其他分享> > 八、龟兔赛跑

八、龟兔赛跑

作者:互联网

案例:

  1. 首先来个赛道距离,然后要离终点越来越近
  2. 判断比赛是否结束
  3. 打印出胜利者
  4. 龟兔赛跑开始
  5. 故事中是乌龟赢的,兔子需要睡觉,所以我们来模拟兔子睡觉
  6. 终于,乌龟赢得比赛

代码:

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;
    }
}

 

结果:

 

标签:赛跑,String,Thread,龟兔,兔子,Race,new,public
来源: https://www.cnblogs.com/epiphany8/p/16268986.html