我一直在为我所在的班级编写比赛代码,该项目有两个线程,一只乌龟和一只野兔。我可以让它们都运行80个单位,但是我不知道如何编写代码来确定并输出获胜者。任何帮助将不胜感激,因为我是编码的新手。

我有乌龟,野兔和raceParticipant类。我的驱动程序类看起来像这样,我假设在哪里放置获胜者代码?

package Domain;

public class Driver
{
    public static void main(String[] args)

    {
        Hare bob = new Hare();
        Tortoise fred = new Tortoise();
        int winDistance = 80;

        do {
            bob.sprint();
            fred.sprint();


            bob.display();
            fred.display();

            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }while(bob.getTotalDistance() < winDistance && fred.getTotalDistance() < winDistance);



}
}


我的冲刺方法是

public int sprint()

{
    int sleep = generator.nextInt(100);
    int sprintDistance = 0;
    if (sleep > sleepPercent)
    {
        sprintDistance = generator.nextInt(topSpeed) + 1;
    }

    totalDistance +=sprintDistance;
    return sprintDistance;
}

最佳答案

我看不到您在任何地方创建新线程。

您可以创建一个Hare类,如下所示:

public class Hare implements Runnable {

    private static final int SLEEP_DURATION = 3000; //milliseconds
    private static final int SPEED = 3; //units per second

    private int distanceToRun;
    private final RaceFinishListener listener;

    public Hare(int distanceToRun, RaceFinishListener listener) {
        this.distanceToRun = distanceToRun;
        this.listener = listener;
    }

    @Override
    public void run() {
        do {
            distanceToRun -= SPEED;
            try {
                Thread.sleep(SLEEP_DURATION);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } while (distanceToRun > 0);
        listener.onRaceFinished(getClass().getSimpleName());
    }
}


以及具有以下变量的类似Tortoise类:

private static final int SLEEP_DURATION = 1000; //sleeps less
private static final int SPEED = 1; //but is slow


然后创建一个侦听器,以在某人完成操作时得到通知:

public interface RaceFinishListener {
    void onRaceFinished(String finisher);
}


最后是你的主要课程:

public class Test implements RaceFinishListener {

    private String winner;
    private static final int DISTANCE_TO_RUN = 10;

    public static void main(String[] args) {
        new Test().race();
    }

    private void race() {
        Hare bob = new Hare(DISTANCE_TO_RUN, this);
        Tortoise fred = new Tortoise(DISTANCE_TO_RUN, this);

        new Thread(bob).start();
        new Thread(fred).start();
    }

    @Override
    public void onRaceFinished(String finisher) {
        synchronized (this) {
            if (winner == null) {
                winner = finisher;
                System.out.println(finisher + " is the winner!");
            } else {
                System.out.println(finisher + " lost.");
            }
        }
    }
}


输出量


  乌龟是赢家!
  野兔迷路了。

09-08 06:41