In this activity we create threads by extending the Thread class.
You will have to add your own classes to the project.
A discussion of the solution can be found in the Solution document.
The task is to simulate the race between the "Hare and the Tortoise".
The class Hare is to extend Thread. Its run() method will contain a for loop that iterates from 1 to 50 000 000, testing each successive value of the loop variable to see if it is divisible by 1 000 000. This can be done by using the condition
if (i % 1000000 == 0)
Whenever the value of the loop variable is divisible by 1000000 (which will happen exactly ten times) the string "H " should be printed, using print() not println() so the output will remain on the same line.
The class Tortoise is to have a run method identical to that of Hare, except that it will print "T " instead of "H ".
A further class ThreadRace1 will contain the main method which creates a Hare instance and a Tortoise instance and sets them running.
When the program executes, a typical printout will show output from the Hare and Tortoise objects interleaved, like this
They're off! H H H H H H T T T T T H H H H T T T T T
On this occasion the hare won (it finished first). On a different occasion the tortoise might be the winner; the outcome is not predictable.
Write classes
as specified above.
You can create a new class by right-clicking on a project or folder and selecting New | Java Class. (You can also use the File| New File dialogue to create each class.)
In the New Class dialogue, create all the classes in the same
package, called race.
Once you've completed your coding, you also need to select the main
class to run.
Run the program several times. You should find that on different runs the race goes differently; sometimes it is won by the hare, sometimes by the tortoise.
(If you make a mistake about where you place a class, you can drag it to the correct folder and select Refactor.)