/*
 * "hello world" program, version 2:
 *
 * creates threads using static inner class (this allows creating each thread 
 * with thread-specific information (myID here)).
 *
 * command-line argument specifies number of threads.
 */
package csci3366.sample.hello;
import csci3366.sample.utility.Utility;

public class Hello2 {

    /* somewhat ugly hack so all threads have access to this value */
    private static int numThreads = 0;

    public static void main(String[] args) {

        /* get number of threads from command line */

        numThreads = Utility.getIntegerArg(args, 0, 1, 
                "numThreads", "arguments:  numThreads");

        /* create threads */

        Thread[] threads = new Thread[numThreads];

        for (int i = 0; i < threads.length; ++i) {
            threads[i] = new Thread(new Inner(i));
        }

        /* start them up */

        System.out.println("starting threads");

        for (int i = 0; i < threads.length; ++i) {
            threads[i].start();
        }

        /* wait for them to finish */

        for (int i = 0; i < threads.length; ++i) {
            try {
                threads[i].join();
            }
            /* must catch -- "checked exception" */
            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_) {
            myID = myID_;
        }

        public void run() {
            System.out.println("hello from " + myID + " of " + numThreads);
        }

    }
}