// Join.java // Introducing the sleep() and join() methods. // Note that the interleaving of thread outputs is not quite perfect. // by Kip Irvine // Updated 1/21/2003 import java.lang.Thread; class MessageThread implements Runnable { public MessageThread( String msg ) { message = msg; } public void run( ) { try { for( int i = 0; i < 20; i++ ) { System.out.println( message + i ); Thread.currentThread( ).sleep( 100 ); } } catch( InterruptedException e ) { } } private String message; } class ThreadDemo { public static void main( String[] args ) { Thread t1 = new Thread ( new MessageThread ( "Thread1: " ) ); Thread t2 = new Thread ( new MessageThread ( "Thread2: " ) ); t1.start( ); t2.start( ); // comment out this try-catch block to see how the program's behavior changes try { t1.join( ); // t1.join( 1000 ) to wait at most 1000 milliseconds t2.join( ); } catch( InterruptedException e ) { } System.out.println( "All threads have finished" ); } }