Java Reference
In-Depth Information
This version produces the same output as before. Notice that the thread is stored in
thrd
inside
MyThread
.
Try This 11-1
Extending Thread
Implementing
Runnable
is one way to create a class that can instantiate thread objects. Ex-
tending
Thread
is the other. In this project, you will see how to extend
Thread
by creating
a program functionally identical to the
UseThreadsImproved
program.
When a class extends
Thread
, it must override the
run( )
method, which is the entry
point for the new thread. It must also call
start( )
to begin execution of the new thread. It
is possible to override other
Thread
methods, but doing so is not required.
1.
Create a file called
ExtendThread.java
. Into this file, copy the code from the second
threading example (
UseThreadsImproved.java
).
2.
Change the declaration of
MyThread
so that it extends
Thread
rather than imple-
menting
Runnable
, as shown here:
3.
Remove this line:
The
thrd
variable is no longer needed, since
MyThread
includes an instance of
Thread
and can refer to itself.
4.
Change the
MyThread
constructor so that it looks like this:
As you can see, first
super
is used to call this version of
Thread
's constructor:
Thread(String
name
);