Check out Callable which is a Runnable that can return a result.
You use it like this:
You write a Callable instead of a Runnable, for example:
public class MyCallable implements Callable<Integer> {
public Integer call () {
// do something that takes really long...
return 1;
}
}
You kick it of by submitting it to an ExecutionService:
ExecutorService es = Executors.newSingleThreadExecutor ();
Future<Integer> task = es.submit(new MyCallable());
You get back the FutureTask handle which will hold the result once the task is finished:
Integer result = task.get ();
FutureTask provides more methods, like cancel
, isDone
and isCancelled
to cancel the execution and ask for the status. The get method itself is blocking and waits for the task to finish. check out the javadoc for details.