# When to use Callable?
If you want the task to produce a value when it's done.
public class CallableDemo {
public static void main(String[] args) {
ExecutorService pool = Executors.newCachedThreadPool();
List<Future<String>> results = new ArrayList<Future<String>>();
for (int i = 0; i < 10; i++) {
results.add(pool.submit(new TaskWithResult(i)));
}
for (Future<String> future : results) {
try {
System.out.println(future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} finally {
pool.shutdown();
}
}
}
}
class TaskWithResult implements Callable<String> {
private int id;
public TaskWithResult(int id) {
this.id = id;
}
@Override
public String call() throws Exception {
return "id: " + id;
}
}
# Future.isDone()
query the Future object to see if it has completed.
#Future.get()
when the task is done, you can fetch the result using get(), or the call to get() will block until the result is ready.
# how to convert a Runnable into Callable?
Executors.callable(runnable);
Executors.callable(runnable, result);