/* * "hello world" program, version 1 * * creates threads using anonymous inner class implementing Runnable. * * environment variable NUM_THREADS specifies number of threads. */ public class Hello1 { public static void main(String[] args) { /* get number of threads from environment variable */ int numThreads = 0; try { String s = System.getenv("NUM_THREADS"); if (s == null) { numThreads = 1; } else { numThreads = Integer.parseInt(s); } } catch (NumberFormatException e) { System.out.println("non-numeric 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 Runnable() { public void run() { System.out.println("hello, world, from thread " + Thread.currentThread().getName()); } }); } /* 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"); } }