/* * "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. * * number of threads is taken from environment variable NUM_THREADS. */ package csci3366sample.hello; import csci3366sample.ThreadUtility; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; public class Hello3 { public static void main(String[] args) { /* get number of threads from environment variable */ int numThreads = 0; try { numThreads = ThreadUtility.getNumThreads(); } catch (ThreadUtility.Exception e) { System.err.println(e.getMessage()); 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); } } }