Implementing the Runnable Interface

 

The ThreadRunnable class uses a different technique than Processus for providing the run method for its thread. Instead of subclassing Thread, ThreadRunnable implements the Runnable interface (and therefore implements the run method defined in it). ThreadRunnable then creates a thread and provides itself as an argument to the Thread's constructor. When created in this way, the Thread gets its run method from the object passed into the constructor.

 

Deciding to Use the Runnable Interface

You have now seen two ways to provide the run method for a Java thread:

 

1.      Subclass the Thread class defined in the java.lang package and override the run method.

 

2.      Provide a class that implements the Runnable interface (also defined in the java.lang package) and therefore implements the run method. In this case, a Runnable object provides the run method to the thread.

 

There are good reasons for choosing either of these options over the other. However, for most cases, the following rule of thumb will guide you to the best option.

 


Rule of Thumb:  If your class must subclass some other class (the most common example being Applet), you should use Runnable as described in option #2.


 

Hosted by www.Geocities.ws

1