In order to execute tasks in parallel, your first choice should be an ExecutorService. You get an instance of one like they say in the docs, that is
ExecutorService service = Executors.newFixedThreadPool(poolSize);
If your tasks must return a value, you should use the
Future<T> submit(Callable<T> task);
function. Make your tasks implement the Callable
interface, returning the result you require. Submit your tasks to the service, then wait for the results through the Future
objects. A rough sketch:
public class MyTask implements Callable<StringInt> {
public MyTask(String inputParameter) { ... }
public StringInt call() { ... }
}
...
List<Future<StringInt>> results = new ArrayList<Future<StringInt>>();
ExecutorService service = Executors.newFixedThreadPool(16);
for (String inputParameter : inputParameters) {
// Create tasks and start parallel execution
results.add(service.submit(new MyTask(inputParameter)));
}
for (Future<StringInt> result : results) {
// Wait for tasks to end, and get result
StringInt resultValue = result.get();
...
}