/* * "hello world" program, version 4: * * uses java.util.concurrent ExecutorService to start threads and assign * them work, another way. * * command-line argument specifies number of threads. */ package csci3366.sample.hello; import csci3366.sample.utility.Utility; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; public class Hello4 { 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, creating Future objects so we * can wait for tasks to finish */ Future[] results = new Future[numThreads]; for (int i = 0; i < results.length; ++i) { results[i] = executor.submit(new Inner(i)); } /* shut down executor and wait for threads to finish */ executor.shutdown(); for (int i = 0; i < results.length; ++i) { try { /* get() returns a value, but we aren't using it */ results[i].get(); } catch (ExecutionException e) { System.err.println("should not happen"); } 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); } } }