Java Reference
In-Depth Information
method before the value has been calculated? This is quite tricky, and we'll discuss it
more later in this chapter.
If you subclass
Thread
, you should override
run()
and nothing else!
The various other methods of the
Thread
class—for example,
start()
,
interrupt()
,
join()
,
sleep()
, and so on—all have very specific se‐
mantics and interactions with the virtual machine that are difficult to
reproduce in your own code. You should override
run()
and provide
additional constructors and other methods as necessary, but you
should not replace any of the other standard
Thread
methods.
Implementing the Runnable Interface
One way to avoid overriding the standard
Thread
methods is not to subclass
Thread
.
Instead, write the task you want the thread to perform as an instance of the
Runnable
interface. This interface declares the
run()
method, exactly the same as the
Thread
class:
public
void
run
()
Other than this method, which any class implementing this interface must provide, you
are completely free to create any other methods with any other names you choose, all
without any possibility of unintentionally interfering with the behavior of the thread.
This also allows you to place the thread's task in a subclass of some other class, such as
Applet
or
HTTPServlet
. To start a thread that performs the
Runnable
's task, pass the
Runnable
object to the
Thread
constructor. For example:
Thread
t
=
new
Thread
(
myRunnableObject
);
t
.
start
();
It's easy to recast most problems that subclass
Thread
into
Runnable
forms.
Example 3-2
demonstrates this by rewriting
Example 3-1
to use the
Runnable
interface rather than
subclassing
Thread
. Aside from the name change, the only modifications that are nec‐
essary are changing
extends Thread
to
implements
Runnable
and passing a
DigestRunnable
object to the
Thread
constructor in the
main()
method. The essential
logic of the program is unchanged.
Example 3-2. DigestRunnable
import
java.io.*
;
import
java.security.*
;
import
javax.xml.bind.*
;
// for DatatypeConverter; requires Java 6 or JAXB 1.0
public
class
DigestRunnable
implements
Runnable
{
private
String
filename
;
public
DigestRunnable
(
String
filename
)
{