Java Reference
In-Depth Information
public
void
run
()
You're going to put all the work the thread does in this one method. This method may
invoke other methods; it may construct other objects; it may even spawn other threads.
However, the thread starts here and it stops here. When the
run()
method completes,
the thread dies. In essence, the
run()
method is to a thread what the
main()
method is
to a traditional nonthreaded program. A single-threaded program exits when the
main()
method returns. A multithreaded program exits when both the
main()
method
and the
run()
methods of all nondaemon threads return. (Daemon threads perform
background tasks such as garbage collection and don't prevent the virtual machine from
exiting.)
Subclassing Thread
Consider a program that calculates the Secure Hash Algorithm (SHA) digest for many
files. To a large extent, this is an I/O-bound program (i.e., its speed is limited by the
amount of time it takes to read the files from the disk). If you write it as a standard
program that processes the files in series, the program is going to spend a lot of time
waiting for the hard drive to return the data. This limit is even more characteristic of
network programs: they execute faster than the network can supply input. Consequent‐
ly, they spend a lot of time blocked. This is time that other threads could use, either to
process other input sources or to do something that doesn't rely on slow input. (Not all
threaded programs share this characteristic. Sometimes, even if none of the threads
have a lot of spare time to allot to other threads, it's simply easier to design a program
by breaking it into multiple threads that perform independent operations.)
Example 3-1
is a subclass of
Thread
whose
run()
method calculates a 256-bit SHA-2
message digest for a specified file. It does this by reading the file with a
DigestInput
Stream
. This filter stream calculates a cryptographic hash function as it reads the file.
When it's finished reading, the hash function is available from the
digest()
method.
Example 3-1. DigestThread
import
java.io.*
;
import
java.security.*
;
import
javax.xml.bind.*
;
// for DatatypeConverter; requires Java 6 or JAXB 1.0
public
class
DigestThread
extends
Thread
{
private
String
filename
;
public
DigestThread
(
String
filename
)
{
this
.
filename
=
filename
;
}
@Override
public
void
run
()
{