Java Reference
In-Depth Information
main program when it's finished. It does this by invoking a method in the main class
that started it. This is called a callback because the thread calls its creator back when it's
done. This way, the main program can go to sleep while waiting for the threads to finish
and not steal time from the running threads.
When the thread's run() method is nearly done, the last thing it does is invoke a known
method in the main program with the result. Rather than the main program asking each
thread for the answer, each thread tells the main program the answer. For instance,
Example 3-5 shows a CallbackDigest class that is much the same as before. However,
at the end of the run() method, it passes off the digest to the static CallbackDigestU
serInterface.receiveDigest() method in the class that originally started the thread.
Example 3-5. CallbackDigest
import java.io.* ;
import java.security.* ;
public class CallbackDigest implements Runnable {
private String filename ;
public CallbackDigest ( 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 ();
byte [] digest = sha . digest ();
CallbackDigestUserInterface . receiveDigest ( digest , filename );
} catch ( IOException ex ) {
System . err . println ( ex );
} catch ( NoSuchAlgorithmException ex ) {
System . err . println ( ex );
}
}
}
The CallbackDigestUserInterface class shown in Example 3-6 provides the main()
method. However, unlike the main() methods in the other variations of this program,
this one only starts the threads for the files named on the command line. It does not
attempt to actually read, print out, or in any other way work with the results of the
calculation. Those functions are handled by a separate method, receiveDigest() ,
which is not invoked by the main() method or by any method that can be reached by
Search WWH ::




Custom Search