|
|
||||
|
||||
|
|
||||
|
||||
|
|
|
|
||||
|
||||
|
|
||||
|
||||
|
|
Code Barn Hello Thread | |
Explanation of HelloThread? applet Number of classes: 1 (HelloThread?.class) What it does: starts a Thread which loops through a run method 10 times, and displays a number for each loop iteration. To run code as a thread requires two things: 1) a Thread object (this is the WORKER) 2) a Runnable object with a run method (the JOB for the WORKER) The HelloThread?.class (an applet subclass) implements the Runnable interface. Run() is the only method required by classes which implement Runnable. The run() method will be called by the Thread object. The class which implements Runnable is the "target" of the Thread object. So in this example, two different objects are used, one for the Thread, and one for the Runnable (target) of the Thread. Using two different objects is the most common way of having code run as a thread, although you can subclass Thread and use the Thread object itself as the Runnable object (Thread implements Runnable) What actually happens in this applet: Two instance variables are declared: one for the Thread object, and one for the GUI Label (used to display a number for each loop the Thread object makes in the run() method of the applet). init() is called:
run() is called:
| |