用java多线程实现:众所周知的“龟兔赛跑”故事,兔子因为太过自信,比赛中途休息而导致乌龟赢得了比赛. 本案例要求编写一个程序模拟龟兔赛跑: 乌龟的速度为0.2米/s 兔子的速度为1米/s 等兔子跑到第700米时选择休息3000s 结果乌龟赢得了比赛。

用java多线程实现:众所周知的“龟兔赛跑”故事,兔子因为太过自信,比赛中途休息而导致乌龟赢得了比赛. 本案例要求编写一个程序模拟龟兔赛跑: 乌龟的速度为0.2米/s 兔子的速度为1米/s 等兔子跑到第700米时选择休息3000s 结果乌龟赢得了比赛。
用户089077750
2023年11月23日
|
浏览 157

好的,以下是用Java多线程实现龟兔赛跑的代码:

复制代码
public class Race {
    public static void main(String[] args) {
        Tortoise tortoise = new Tortoise();
        Hare hare = new Hare();

        tortoise.start();
        hare.start();

        try {
            tortoise.join();
            hare.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (tortoise.getPosition() >= 700) {
            System.out.println("乌龟赢得了比赛!");
        } else {
            System.out.println("兔子赢得了比赛!");
        }
    }
}

class Tortoise extends Thread {
    private int position;

    public int getPosition() {
        return position;
    }

    @Override
    public void run() {
        double speed = 0.2;
        int restDistance = 700;

        while (position < restDistance) {
            position += speed;
            System.out.println("乌龟跑了 " + position + " 米");
        }
    }
}

class Hare extends Thread {
    private int position;

    public int getPosition() {
        return position;
    }

    @Override
    public void run() {
        double speed = 1;
        int restDistance = 700;
        int restTime = 3000;

        while (position < restDistance) {
            position += speed;
            System.out.println("兔子跑了 " + position + " 米");

            if (position >= 700) {
                try {
                    Thread.sleep(restTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

请注意,这只是一个简单的模拟,实际比赛中的因素可能更加复杂。

我要提问
复制内容
分享给好友
AI编程问答网 免责声明:
以上内容除特别注明外均来源于网友提问,AI编程问答网回答,权益归原著者所有;