The code submits a Callable
100 times to an ExecutorService
containing 10 threads and captures the Futures that indicate when each Callable has been run.
ExecutorService executor = Executors.newFixedThreadPool(10);
List<Future<String>> list = new ArrayList<Future<String>>();
Callable<String> callable = new MyCallable();
for (int i = 0; i < 100; i++)
{
Future<String> future = executor.submit(callable);
list.add(future);
}
Once each of the 10 threads are running a Callable the remaining Callables will be queued up and are run as each thread becomes available.
After all the Callables have been added, the next block of code gets the result from each Future, the important thing being that the calling thread will block on the call to Future.get until the Callable finishes, so the results will be printed in the order the Callables were added.
for(Future<String> fut : list)
{
try
{
System.out.println(new Date() + "::" + fut.get());
}
catch (InterruptedException | ExecutionException e)
{
e.printStackTrace();
}
}
Finally the executor is shutdown to kill the threads it contains.
executor.shutdown();