/* * "hello world" program, version 3: * * uses java.util.concurrent ExecutorService to start threads and assign * them work, one way. * * command-line argument specifies number of threads. */ package csci3366.sample.hello; import csci3366.sample.utility.Utility; 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 command line */ int numThreads = Utility.getIntegerArg(args, 0, 1, "numThreads", "arguments: numThreads"); /* 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_) { myID = myID_; } public void run() { System.out.println("hello from " + myID); } } }