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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM