Java Reference
In-Depth Information
8.2.2 Thread creation: Runnable
In the second threading technique a class implements the
Runnable
interface
and overrides its
run()
method. This approach is often convenient, especially
for cases where you want to create a single instance of a thread, as in an animation
for an applet. You pass a reference to the
Runnable
object via the constructor
of
Thread
and when it starts, the thread
calls back
to the
run()
method. As
before, the thread process dies after exiting
run()
.
The following code segment illustrates this approach. Here
MyRunnableAp-
plet
implements the
Runnable
interface. The
start()
method creates an
instance of the
Thread
class and passes a reference to itself (with the
“this
„
reference) in the thread's constructor. When it invokes the
start()
method for
the thread, the thread will invoke the
run()
method in
MyRunnableApplet
.
/** Demo threading with Runnable implementation. **/
public class
MyRunnableApplet
extends java.applet.Applet
implements Runnable
{
/** Applet's start method creates a thread. **/
public void start () {
// Create an instance of Thread with a
// reference to this Runnable instance.
Thread thread = new Thread (this);
// Start the thread
thread.start ();
} // start
/** Override the Runnable run() method. **/
public void run ()
{
int count
=
0;
while (true)
{
System.out.println (
"
Thread alive
"
);
// Print every 0.10sec for 5 seconds
try
{
Thread.sleep(100);
} catch (InterruptedException e) {}
count++;
if (count >= 50) break;
}
System.out.println ("Thread stopping");
} // run
public void paint (java.awt.Graphics g) {
Search WWH ::
Custom Search