Java多线程(四): 龟兔赛跑案例

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

public class Race implements Runnable {
    public static boolean isGameOver = false;

    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        for (int i = 0; i < 100; i++) {

            if (!isGameOver) {
                System.out.println(name + " has run " + i + " steps.");
            }else {
                break;
            }

            if(i == 30 && name == "Rabbit"){
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            if (i == 99) {
                isGameOver = true;
                System.out.println(name + " wins!");
            }
        }


    }


    public static void main(String[] args) {
        new Thread(new Race(), "Rabbit").start();
        new Thread(new Race(), "Turtle").start();
    }
}
posted @ 2020-05-23 19:42  Archer_Shu  阅读(1171)  评论(0编辑  收藏  举报