Discussion of Activity 8.1 - Running the hare and the tortoise race

Sample solution

Code for class Hare:

public class Hare extends Thread
{
public void run()
{
for (int i = 1; i <= 50000000; i++)
{
if (i % 1000000 == 0)
{
System.out.print("H ");
}
}
}
}

Code for class Tortoise:

public class Tortoise extends Thread
{
public void run()
{
for (int i = 1; i <= 50000000; i++)
{
if (i % 1000000 == 0)
{
System.out.print("T ");
}
}
}
}

Code for running the race ThreadRace1:

public class ThreadRace1
{
public static void main(String[] args)
{
Hare h = new Hare();
Tortoise t = new Tortoise();
System.out.print("They're off! ");
h.start();
t.start();
}
}

Note

Scroll the output window to the right to see the winner.

You may need to run your code several times to see a change in the winner. If you don't ever see a change in the winner, you might
try adding a 0 to the number of iterations and to the remainder expression.