其他分享
首页 > 其他分享> > 02案例龟兔赛跑

02案例龟兔赛跑

作者:互联网

案例:龟兔赛跑

package edu.wzw.Thread;

public class Race implements Runnable{
    private static String Winner;
    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            //模拟兔子睡眠
            if (Thread.currentThread().getName().equals("兔子") && i%10==0){
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }//模拟乌龟专属龟速
            if (Thread.currentThread().getName().equals("乌龟") ){
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }//判断是否完成比赛
            boolean flag=gameOver(i);
            if(flag){//如果比赛结束了,就停止程序
                break;
            }
            System.out.println(Thread.currentThread().getName()+"跑了"+i+"米");
        }
    }//判断是否完成比赛
    private boolean gameOver(int step) {
        if (Winner != null) {//判断是否有胜利者
            return true;
            }
        {
            if (step >= 100) {
                Winner = Thread.currentThread().getName();
                System.out.println("百米冠军是 " + Winner);
                return true;
            }
        }
        return false;
    }
    public static void main(String[] args) {
        Race race = new Race();
        new Thread(race,"兔子").start();
        new Thread(race,"乌龟").start();
    }
}

标签:02,赛跑,Winner,currentThread,Thread,getName,龟兔,兔子,乌龟
来源: https://blog.csdn.net/dekudekuku/article/details/118255564