Java Reference
In-Depth Information
object as an argument. You could create a threaded
StockTicker
object with the follow-
ing statement:
StockTicker tix = new StockTicker();
Thread tickerThread = new Thread(tix);
Two good places to create threads are the constructor for an application and the construc-
tor for a component (such as a panel).
A thread is begun by calling its
start()
method, as in the following statement:
tickerThread.start();
The following statements can be used in a thread class to start the thread:
Thread runner;
if (runner == null) {
runner = new Thread(this);
runner.start();
}
The
this
keyword used in the
Thread()
constructor refers to the object in which these
statements are contained. The
runner
variable has a value of
null
before any object is
assigned to it, so the
if
statement is used to make sure that the thread is not started more
than once.
To run a thread, its
start()
method is called, as in this statement from the preceding
example:
runner.start();
Calling a thread's
start()
method causes another method to be called—namely, the
run()
method that must be present in all threaded objects.
The
run()
method is the engine of a threaded class. In the introduction to threads, they
were described as a means of segregating processor-intensive work so that it ran sepa-
rately from the rest of a class. This kind of behavior would be contained within a
thread's
run()
method and the methods that it calls.
A Threaded Application
Threaded programming requires a lot of interaction among different objects, so it should
become clearer when you see it in action.
7
Listing 7.3 contains a class that finds a specific prime number in a sequence, such as the
10th prime, 100th prime, or 1,000th prime. This can take some time, especially for num-
bers beyond 100,000, so the search for the right prime takes place in its own thread.