java--龟兔赛跑模拟

Posted lee-leo

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java--龟兔赛跑模拟相关的知识,希望对你有一定的参考价值。

//龟兔赛跑
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--龟兔赛跑模拟的主要内容,如果未能解决你的问题,请参考以下文章

java--龟兔赛跑模拟

Java多线程模拟龟兔赛跑

java多线程模拟龟兔赛跑

蓝桥杯 BASIC 24 龟兔赛跑预測(模拟)

java中线程的两种创建方式

多线程模拟龟兔赛跑游戏