Java Reference
In-Depth Information
Lab 15.1: Creating a Thread
To become familiar with creating a thread by implementing the Runnable
interface.
1. Write a class named PrintNumbers that implements the Runnable
interface. Add a field of type boolean called keepGoing and a con-
structor that initializes keepGoing to true.
2. Add a method to the PrintNumbers class called stopPrinting() that
assigns the keepGoing field to false.
3. Within the run() method, write a while loop using
System.out.printl(), which prints out the numbers 1, 2, 3, 4, and so
on for as long as the keepGoing field is true. In between printing
each number, the thread should sleep for 1 second.
4. Save and compile the PrintNumbers class.
5. Write a class named Print that contains main(). Within main(),
instantiate a PrintNumbers object. Instantiate a Thead object that
will be used to run the PrintNumbers object in a separate thread and
then start the thread.
6. The Print program will take in a single command-line argument to
represent the number of milliseconds that the main() thread will
sleep. Parse this argument into an int and then have the main()
thread sleep for that amount of milliseconds.
7. When the main() thread wakes up, have it invoke the stopPrinting()
method on the PrintNumbers object.
8. Save, compile, and run the Print program. Don't forget to pass in an
int to represent how long the program will run in milliseconds.
The numbers 1, 2, 3, and so on will be printed for approximately the
number of seconds you specified with the command-line argument. For
example, if the command-line argument is 10,000, you should see about
10 numbers printed. This lab demonstrates a common need in thread
programming: creating a mechanism for a thread to stop executing. The
stopPrinting() method can be invoked from any other thread to inform
PrintNumbers that it should stop running.
Search WWH ::




Custom Search