Java Reference
In-Depth Information
Lab 15.2: Simulating a Car Race
To become familiar with writing a thread by extending the Thread class.
1. Write a class named RaceCar that extends the Thread class and con-
tains the run() method.
2. Add an int field named finish and a String field called name. Add a
constructor that initializes both fields.
3. Within run(), add a for loop that executes finish number of times.
Within the for loop, use System.out.println() to print out the name
field and also the current iteration through the loop. For example,
the third time through the loop should output “Mario: 3” for a car
named Mario. Then, have the thread sleep for a random amount of
time between 0 and 5 seconds.
4. At the end of the for loop, print out a message stating that the race
car has finished the race, and print out the name field as well. For
example, “Mario finished!”
5. Save and compile the RaceCar class.
6. Write a class named Race that contains main().
7. Within main(), declare and create an array large enough to hold five
Thread references.
8. Write a for loop that fills the array with five RaceCar objects. The
names should be retrieved from five command-line arguments, and
the int should be the same for each RaceCar. This value will repre-
sent how long the race will last, and it should also be input from the
command line.
9. Write a second for loop that invokes start() on each Thread in the
array.
10. Save, compile, and run the Race program.
The Race program will look like a car race that slowly progresses as
you watch it. The winner will be whichever RaceCar thread reaches the
finish line first.
Search WWH ::




Custom Search