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
digest as in Example 5.1 and Example 5.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, then provide a getter method, as
shown in Example 5.3 and Example 5.4. Example 5.3 is a
Thread
subclass that calculates a digest for a
specified file. Example 5.4 is a simple command-line
user interface that receives filenames and spawns threads to
calculate digests for them.
Example 5-3. A Thread That Uses an Accessor Method to Return the Result
import java.io.*; import java.security.*; public class ReturnDigest extends Thread { private File input; private byte[] digest; public ReturnDigest(File input) { this.input = input; } public void run( ) { try { FileInputStream in = new FileInputStream(input); MessageDigest sha = MessageDigest.getInstance("SHA"); DigestInputStream din = new DigestInputStream(in, sha); int b; while ((b = din.read( )) != -1) ; din.close( ); digest = sha.digest( ); } catch (IOException e) { System.err.println(e); ...
Get Java Network Programming, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.