Getting results from a thread
In our examples so far, we have used the execute()
method of the ExecutorService
interface to start a thread. In fact, this method comes from the Executor
base interface. Meanwhile, the ExecutorService
interface has other methods (listed in the previous Using a pool of threads section) that can start threads and get back the results of thread execution.
The object that brings back the result of thread execution is of type Future
—an interface that has the following methods:
V get()
: Blocks until the thread finishes; returns the result (if available)V get(long timeout, TimeUnit unit)
: Blocks until the thread finishes or the provided timeout is up; returns the result (if available)boolean isDone()
: Returnstrue
if the thread has finishedboolean cancel(boolean mayInterruptIfRunning)
: Tries to cancel the execution of the thread; returnstrue
if successful; returnsfalse
also in the case the thread had finished normally by the...