/*
 * "hello world" program, version 3
 *
 * creates threads using static inner class (which allows creating each
 *   thread with thread-specific information) and Java 1.5 features.
 *
 * command-line argument specifies number of threads.
 */
import java.util.concurrent.*;

public class Hello3 {

    public static void main(String[] args) {

        /* process command-line argument */

        if (args.length <= 0) {
            System.err.println("usage:  Hello3 numThreads");
            System.exit(1);
        }
        int numThreads = 0;
        try {
            numThreads = Integer.parseInt(args[0]);
        }
        catch (NumberFormatException e) {
            System.err.println("usage:  Hello3 numThreads");
            System.exit(1);
        }

        /* create executor for threads */

        ExecutorService executor = Executors.newFixedThreadPool(numThreads);

        /* create tasks and send to executor */

        for (int i = 0; i < numThreads; ++i) {
            executor.execute(new Inner(i));
        }

        /* wait for threads to finish */

        executor.shutdown();
        try {
            executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        }
        catch (InterruptedException e) {
            System.err.println("should not happen");
        }
        System.out.println("threads all done");

    }

    /* inner class containing code for each thread to execute */

    private static class Inner implements Runnable {

        private int myID;

        public Inner(int myID) {
            this.myID = myID;
        }

        public void run() {
            System.out.println("hello from " + myID);
            try {
                Thread.sleep(10);
            }
            catch (InterruptedException e) {
                System.err.println("should not happen");
            }
            System.out.println("hello again from " + myID);
        }

    }
}