Java Reference
In-Depth Information
The
Thread
Class
A thread is an object of the class
Thread
. The normal way to program a thread is to define a
class that is a derived class of the class
Thread
. An object of this derived class will be a
thread that follows the programming given in the definition of the derived (thread) class's
method named
run
.
Any thread class inherits the method start from the class
Thread
. An invocation of
start
by an object of a thread class will start the thread and invoke the method
run
for that thread.
See Display 19.2 for an example.
The
Runnable
Interface
★
There are times when you would rather not make a thread class a derived class of the
class
Thread
. The alternative to making your class a derived class of the class Thread is
to have your class instead implement the
Runnable
interface. The
Runnable
interface
has only one method heading:
public
void
run()
A class that implements the
Runnable
interface must still be run from an instance of
the class
Thread
. This is usually done by passing the
Runnable
object as an argument
to the thread constructor. The following is an outline of one way to do this:
public
class
ClassToRun
extends
SomeClass
implements
Runnable
{
....
public
void
run()
{
//Fill this just as you would if ClassToRun
//were derived from Thread.
}
....
public
void
startThread()
{
Thread theThread =
new
Thread(
this
);
theThread.run();
}
....
}
The above method
startThread
is not compulsory, but it is one way to produce a
thread that will in turn run the
run
method of an object of the class
ClassToRun
. In
Display 19.3 we have rewritten the program in Display 19.2 using the
Runnable
inter-
face. The program behaves exactly the same as the one in Display 19.2.