| ||||
Copyright 1999 Sams Publishing |
|
Passing a Runnable Object to a Threads Constructor |
The Thread class has four constructors that take a Runnable object as a parameter: |
public Thread(Runnable target) |
public Thread(Runnable target, String name ) |
public Thread(ThreadGroup group , Runnable target) |
public Thread(ThreadGroup group, Runnable target, String name) |
Any instance of a class that implements the Runnable interface may be passed as the target to one of these constructors. When the Thread instances start() method is invoked, start() will start the new thread in the run() method of target rather than in Thread s run() method. The Runnable to be used may be specified only at the time of a Thread s construction; the Thread holds a reference to it in a private member variable. |
Because SecondCounter now implements Runnable , a new Thread instance should be created with a SecondCounter instance for a target , like this: |
SecondCounter sc = new SecondCounter(); |
Thread t = new Thread(sc); |
t.start(); |
When t.start() is executed, the newly spawned thread will begin execution by invoking the run() method of SecondCounter . Figure 4.6 presents the resulting object diagram. Note that Thread HAS-A reference to a Runnable (which in this case is more specifically a SecondCounter ). |
Figure 4.6: The object diagram for a Runnable SecondCounter passed as a target to a Thread constructor. | |
Tip | Implementing the Runnable interface, rather than extending Thread , is generally a better choice, even if the class only inherits from Object . This allows you to develop and use general techniques with classes that implement the Runnable interface, without any concern for which particular class this Runnable extended . |
| |||
Toc |