|
|
Threads of Control |
All the action takes place in the thread body, which is the thread'srunmethod. After a thread has been created and initialized, the runtime system calls itsrunmethod. The code in therunmethod implements the behavior for which the thread was created. It's the thread's raison d'etre.Often, a thread's
runmethod is a loop. For example, an animation thread might loop through and display a series of images. Sometimes a thread'srunmethod performs an operation that takes a long time, for example, downloading and playing a sound or a JPEG movie.You can choose one of two ways to provide a customized
runmethod for a Java thread: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.
- Subclass the
Threadclass defined in thejava.langpackage and override therunmethod.
Example: TheSimpleThreadclass described in A Simple Thread Example.
- Provide a class that implements the
Runnableinterface, also defined in thejava.langpackage. Now, when you instantiate a thread (either directly from theThreadclass, or from a subclass ofThread), give the new thread a handle to an instance of yourRunnableclass. ThisRunnableobject provides therunmethod to the thread.
Example: The Clock applet you see on the following page.
Rule of thumb: If your class must subclass some other class (the most common example beingApplet), you should useRunnableas described in option #2.
|
|
Threads of Control |