Java Reference
In-Depth Information
All processes have at least one thread of execution, which is usually called the
main
thread
, because it is the one that is executed when your program begins. Thus, the main
thread is the thread that all of the preceding example programs in the topic have been using.
From the main thread, you can create other threads.
Creating a Thread
You create a thread by instantiating an object of type
Thread
. The
Thread
class encap-
sulates an object that is runnable. As mentioned, Java defines two ways in which you can
create a runnable object:
You can implement the
Runnable
interface.
You can extend the
Thread
class.
Most of the examples in this chapter will use the approach that implements
Runnable
.
However,
Try This 11-1
shows how to implement a thread by extending
Thread
. Remem-
ber: Both approaches still use the
Thread
class to instantiate, access, and control the thread.
The only difference is how a thread-enabled class is created.
The
Runnable
interface abstracts a unit of executable code. You can construct a thread
on any object that implements the
Runnable
interface.
Runnable
defines only one method
called
run( )
, which is declared like this:
Inside
run( )
, you will define the code that constitutes the new thread. It is important to
understand that
run( )
can call other methods, use other classes, and declare variables just
like the main thread. The only difference is that
run( )
establishes the entry point for an-
other, concurrent thread of execution within your program. This thread will end when
run(
)
returns.
After you have created a class that implements
Runnable
, you will instantiate an object
of type
Thread
on an object of that class.
Thread
defines several constructors. The one
that we will use first is shown here:
Thread(Runnable
threadOb
)
In this constructor,
threadOb
is an instance of a class that implements the
Runnable
inter-
face. This defines where execution of the thread will begin.
Once created, the new thread will not start running until you call its
start( )
method,
which is declared within
Thread
. In essence,
start( )
executes a call to
run( )
. The
start( )
method is shown here: