/** * Create 8 child threads, let them sleep, * then monitor when they terminate */ public class Octuplets { // This is the thread code itself class Child extends Thread { public void run() { int t = 10 + (int)( Math.random() * 21 ); // 10-30 seconds System.out.println( "THREAD: I'm new. I'm gonna nap for " + t + " seconds." ); try { Thread.sleep( t * 1000 ); // milliseconds } catch( InterruptedException ex ) { /* ... */ } } } // This is the main thread public void manageThreads() { int children = 8; Thread[] threads = new Thread[ children ]; // Create the Thread objects for ( int i = 0 ; i < children ; i++ ) { threads[i] = new Thread( new Child() ); } // START the threads for ( int i = 0 ; i < children ; i++ ) { threads[i].start(); } System.out.println( "MAIN THREAD: I'm waiting for my children." ); int n = children; while ( n > 0 ) { for ( int i = 0 ; i < children ; i++ ) { if ( threads[i] != null && threads[i].isAlive() == false ) { /* detected a thread that has completed its execution */ try { threads[i].join(); } catch( InterruptedException ex ) { /* ... */ } System.out.println( "MAIN THREAD: caught a thread." ); threads[i] = null; n--; System.out.println( "MAIN THREAD: " + n + " more to go..." ); } } } } public static void main( String[] args ) { Octuplets object = new Octuplets(); object.manageThreads(); } }