What is the advantage of using ExecutorService over running threads passing a Runnable into the Thread constructor?
ExecutorService also gives access to FutureTask which will return to the calling class the results of a background task once completed. In the case of implementing Callable
public class TaskOne implements Callable {
@Override
public String call() throws Exception {
String message = "Task One here. . .";
return message;
}
}
public class TaskTwo implements Callable {
@Override
public String call() throws Exception {
String message = "Task Two here . . . ";
return message;
}
}
// from the calling class
ExecutorService service = Executors.newFixedThreadPool(2);
// set of Callable types
Set>callables = new HashSet>();
// add tasks to Set
callables.add(new TaskOne());
callables.add(new TaskTwo());
// list of Future types stores the result of invokeAll()
List>futures = service.invokeAll(callables);
// iterate through the list and print results from get();
for(Futurefuture : futures) {
System.out.println(future.get());
}