1 package template;
2 
3 public class ThreadWaiter {
4 
5 	/** Wait for completion of all threads */
waitForThreads(Iterable<T> iter)6 	public static final <T extends Thread> boolean waitForThreads(Iterable<T> iter){
7 
8 		//Wait for completion of all threads
9 		boolean success=true;
10 		for(T t : iter){
11 
12 			//Wait until this thread has terminated
13 			while(t.getState()!=Thread.State.TERMINATED){
14 				try {
15 					//Attempt a join operation
16 					t.join();
17 				} catch (InterruptedException e) {
18 					//Potentially handle this, if it is expected to occur
19 					e.printStackTrace();
20 				}
21 			}
22 		}
23 
24 		return success;
25 	}
26 
startThreads(Iterable<T> iter)27 	public static final <T extends Thread> void startThreads(Iterable<T> iter){
28 		for(Thread t : iter){t.start();}
29 	}
30 
31 	/**
32 	 * @param iter List of Threads.
33 	 * @return success
34 	 */
startAndWait(Iterable<T> iter)35 	public static final <T extends Thread> boolean startAndWait(Iterable<T> iter){
36 		startThreads(iter);
37 		return waitForThreads(iter);
38 	}
39 
40 	/**
41 	 * @param iter List of Threads.
42 	 * @return success
43 	 */
startAndWait(Iterable<T> iter, Accumulator<T> acc)44 	public static final <T extends Thread> boolean startAndWait(Iterable<T> iter, Accumulator<T> acc){
45 		startThreads(iter);
46 //		assert(false);
47 		return waitForThreads(iter, acc);
48 	}
49 
50 	/** Wait for completion of all threads, and accumulate results */
waitForThreads(Iterable<T> iter, Accumulator<T> acc)51 	public static final <T extends Thread> boolean waitForThreads(Iterable<T> iter, Accumulator<T> acc){
52 
53 		waitForThreads(iter);
54 		accumulate(iter, acc);
55 		return acc.success();
56 
57 	}
58 
59 	/** Accumulate results from all threads */
accumulate(Iterable<T> iter, Accumulator<T> acc)60 	private static final <T> boolean accumulate(Iterable<T> iter, Accumulator<T> acc){
61 
62 		//Wait for completion of all threads
63 		for(T t : iter){
64 //			assert(t.getState()==Thread.State.TERMINATED);//Not strictly necessary; requires T to be a thread.
65 
66 			//Accumulate per-thread statistics
67 			acc.accumulate(t);
68 		}
69 
70 		return acc.success();
71 	}
72 
73 }
74