Java Reference
In-Depth Information
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
)
;
din
.
close
();
byte
[]
digest
=
sha
.
digest
();
StringBuilder
result
=
new
StringBuilder
(
filename
);
result
.
append
(
": "
);
result
.
append
(
DatatypeConverter
.
printHexBinary
(
digest
));
System
.
out
.
println
(
result
);
}
catch
(
IOException
ex
)
{
System
.
err
.
println
(
ex
);
}
catch
(
NoSuchAlgorithmException
ex
)
{
System
.
err
.
println
(
ex
);
}
}
public
static
void
main
(
String
[]
args
)
{
for
(
String
filename
:
args
)
{
DigestRunnable
dr
=
new
DigestRunnable
(
filename
);
Thread
t
=
new
Thread
(
dr
);
t
.
start
();
}
}
}
There's no strong reason to prefer implementing
Runnable
to extending
Thread
or vice
versa in the general case. In a few special cases, such as
Example 3-14
later in this chapter,
it may be useful to invoke some instance methods of the
Thread
class from within the
constructor for each
Thread
object. This requires using a subclass. In other specific
cases, it may be necessary to place the
run()
method in a class that extends another
class, such as
HTTPServlet
, in which case the
Runnable
interface is essential. Finally,
some object-oriented purists argue that the task that a thread undertakes is not really a
kind of
Thread
, and therefore should be placed in a separate class or interface such as
Runnable
rather than in a subclass of
Thread
. I half agree with them, although I don't
think the argument is as strong as it's sometimes made out to be. Consequently, I'll
mostly use the
Runnable
interface in this topic, but you should feel free to do whatever
seems most convenient.