Previous | Next | Trail Map | Writing Java Programs | Threads of Control


Thread Body

All the action takes place in the thread body which is the thread's run() method. After a thread has been created and initialized, the runtime system calls its run() method. The code in the run() method implements the behavior for which the thread was created. It's the thread's raison d'etre.

Often, a thread's run() method is a loop. For example, an animation thread might loop through and display a series of images. Sometimes a thread's run() method performs an operation that takes a long time. For example, downloading and playing a sound or a JPEG movie.

There are two different ways that you can provide a customized run() method for a Java thread:

  1. Subclass the Thread class defined in the java.lang package and override the run() method.
    Example: The SimpleThread class used in the the example described in A Simple Thread Example previously in this lesson is an example of this style of using Java threads.
  2. Provide a class that implements the Runnable interface, also defined in the java.lang package. Now, when you instantiate a thread (either directly from the Thread class, or from a subclass of Thread), give the new thread a handle to an instance of your Runnable class. This Runnable object provides the run() method to the thread.
    Example: The clock applet you see here is an example of using the Runnable interface to provide a run() method to a thread. The Clock Applet describes the source code for this simple applet.
There are good reasons for choosing either of the two options described above 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.


Previous | Next | Trail Map | Writing Java Programs | Threads of Control