Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Sounds like you want <code><a href="http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html#invokeAll%28java.util.Collection%29" rel="noreferrer">ExecutorService.invokeAll</a></code>, which will return results from worker threads in a fixed order, even though they may be scheduled in arbitrary order:</p> <pre><code>import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class ThreadOrdering { static int NUM_THREADS = 10; public static void main(String[] args) { ExecutorService exec = Executors.newFixedThreadPool(NUM_THREADS); class MyCallable implements Callable&lt;Integer&gt; { private final int threadnumber; MyCallable(int threadnumber){ this.threadnumber = threadnumber; } public Integer call() { System.out.println("Running thread #" + threadnumber); return threadnumber; } } List&lt;Callable&lt;Integer&gt;&gt; callables = new ArrayList&lt;Callable&lt;Integer&gt;&gt;(); for(int i=1; i&lt;=NUM_THREADS; i++) { callables.add(new MyCallable(i)); } try { List&lt;Future&lt;Integer&gt;&gt; results = exec.invokeAll(callables); for(Future&lt;Integer&gt; result: results) { System.out.println("Got result of thread #" + result.get()); } } catch (InterruptedException ex) { ex.printStackTrace(); } catch (ExecutionException ex) { ex.printStackTrace(); } finally { exec.shutdownNow(); } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload