码迷,mamicode.com
首页 > 编程语言 > 详细

java--龟兔赛跑模拟

时间:2020-05-31 21:29:04      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:start   bool   lag   OLE   else   比赛   public   turn   cep   

//龟兔赛跑
public class Race implements Runnable{
    private static String winner;
    @Override
    public void run() {
        for (int i = 0; i <= 100 ;) {
            //模拟兔子休息
            if (Thread.currentThread().getName().equals("兔子") && i%20==0){
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            boolean flag = gameOver(i);
            if (flag){
                break;
            }
            if (Thread.currentThread().getName().equals("兔子")){
                i += 10;
            }else {
                i++;
            }
            System.out.println(Thread.currentThread().getName()+"-->跑了"+i+"步");
        }
    }
    //判断是否完成比赛
    private boolean gameOver(int steps){
        if (winner != null){
            return true;
        }
        if (steps == 100){
            winner = Thread.currentThread().getName();
            System.out.println("winner is "+winner);
            return true;
        }
        return false;
    }
    public static void main(String[] args) {
        Race race = new Race();
        new Thread(race,"兔子").start();
        new Thread(race,"乌龟").start();
    }
}

java--龟兔赛跑模拟

标签:start   bool   lag   OLE   else   比赛   public   turn   cep   

原文地址:https://www.cnblogs.com/lee-leo/p/13021501.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!