Java Reference
In-Depth Information
g.drawString (
"
Thread demo 2
"
,20,20);
}
}
// class MyRunnableApplet
The diagram in Figure 8.2 shows schematically how this approach works.
8.2.3
Thread
subclass vs.
Runnable
The choice between these two thread creation techniques depends on the particular
application and what seems most appropriate and convenient for it. Since Java
does not allow multiple inheritance, an applet class that is already a subclass of
Applet
or
JApplet
can become multithreaded by implementing
Runnable
.
The
run()
method will have access to the variables and methods of the class.
Forexample, an applet animation may need parameters for initialization and may
also need to invoke methods from the applet.
Extending
Thread
applies well to the situation where you want to create a
specialized thread class that does not need to extend any other class. A common
case is where many
worker
threads are needed such as in a server program that
Figure 8.2
This diagram illustrates threading with a
Runnable
class.
MyRunnableApplet
implements the
Runnable
interface and it creates an instance of
Thread
and passes in the constructor a reference to itself as a
Runnable
object. (We
use the name
“
runnable
” for the reference variable to the
Runnable
object.) The
applet invokes the
start()
method for the thread and it returns while the thread
process continues independently with the invocation of the
run()
method
in
the
applet object. When the thread process returns from the applet's
run()
the thread
dies.
Search WWH ::
Custom Search