/* * "hello world" program, version 2 * * creates threads using static inner class. this allows creating each * thread with thread-specific information (myID here). * * number of threads is taken from environment variable NUM_THREADS. */ public class Hello2a { private static final String NUM_THREADS_VAR = "NUM_THREADS"; public static void main(String[] args) { /* look up environment variable */ String numThreadsEnvVar = System.getenv(NUM_THREADS_VAR); if (numThreadsEnvVar == null) { System.err.println("environment variable NUM_THREADS must be set"); System.exit(1); } int numThreads = 0; try { numThreads = Integer.parseInt(numThreadsEnvVar); } catch (NumberFormatException e) { System.err.println("invalid value for NUM_THREADS"); System.exit(1); } /* create threads */ Thread[] threads = new Thread[numThreads]; for (int i = 0; i < numThreads; ++i) { threads[i] = new Thread(new Inner(i)); } /* start them up */ System.out.println("starting threads"); for (int i = 0; i < numThreads; ++i) { threads[i].start(); } /* wait for them to finish */ for (int i = 0; i < numThreads; ++i) { try { threads[i].join(); } catch (InterruptedException e) { System.err.println("this 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); } } }