Java Reference
In-Depth Information
Returning Information from a Thread
One of the hardest things for programmers accustomed to traditional, single-threaded
procedural models to grasp when moving to a multithreaded environment is how to
return information from a thread. Getting information out of a finished thread is one
of the most commonly misunderstood aspects of multithreaded programming. The
run()
method and the
start()
method don't return any values. For example, suppose
that instead of simply printing out the SHA-256 digest, as in Examples
3-1
and
3-2
, the
digest thread needs to return the digest to the main thread of execution. Most people's
first reaction is to store the result in a field and provide a getter method, as shown in
Examples
3-3
and
3-4
.
Example 3-3
is a
Thread
subclass that calculates a digest for a
specified file.
Example 3-4
is a simple command-line user interface that receives file‐
names and spawns threads to calculate digests for them.
Example 3-3. A thread that uses an accessor method to return the result
import
java.io.*
;
import
java.security.*
;
public
class
ReturnDigest
extends
Thread
{
private
String
filename
;
private
byte
[]
digest
;
public
ReturnDigest
(
String
filename
)
{
this
.
filename
=
filename
;
}
@Override
public
void
run
()
{
try
{
FileInputStream
in
=
new
FileInputStream
(
filename
);
MessageDigest
sha
=
MessageDigest
.
getInstance
(
"SHA-256"
);
DigestInputStream
din
=
new
DigestInputStream
(
in
,
sha
);
while
(
din
.
read
()
!=
-
1
)
;
// read entire file
din
.
close
();
digest
=
sha
.
digest
();
}
catch
(
IOException
ex
)
{
System
.
err
.
println
(
ex
);
}
catch
(
NoSuchAlgorithmException
ex
)
{
System
.
err
.
println
(
ex
);
}
}
public
byte
[]
getDigest
()
{
return
digest
;
}
}