Java Reference
In-Depth Information
just reads from the console terminal, and the main thread simply waits for it. When I run the
program, it looks like this:
darwinsys.com$ java threads.Join
Starting
Joining
Reading
hello from standard input # waits indefinitely for me to type this line
Thread Finished.
Main Finished.
darwinsys.com$
Example 22-9 lists the code for the join( ) demo.
Example 22-9. Join.java
public
public class
class Join
Join {
public
public static
void main ( String [] args ) {
Thread t = new
static void
new Thread () {
public
public void
void run () {
System . out . println ( "Reading" );
try
try {
System . in . read ();
} catch
catch ( java . io . IOException ex ) {
System . err . println ( ex );
}
System . out . println ( "Thread Finished." );
}
};
System . out . println ( "Starting" );
t . start ();
System . out . println ( "Joining" );
try
try {
t . join ();
} catch
catch ( InterruptedException ex ) {
// should not happen:
System . out . println ( "Who dares interrupt my sleep?" );
}
System . out . println ( "Main Finished." );
}
}
As you can see, it uses an inner class Runnable (see Running Code in a Different Thread ) in
Thread t to be runnable.
Search WWH ::




Custom Search