Java Reference
In-Depth Information
(You may get a different output.)
Task #1 - Iteration #1 is going to sleep for 8 seconds.
Task #1 - Iteration #2 is going to sleep for 9 seconds.
Task #1 - Iteration #3 is going to sleep for 5 seconds.
Task's total sleep time: 22 seconds
I will explain the logic in the two listings step by step:
CallableTask class defines the call() method, which contains the logic for task
processing. It sums up all the sleep times for the task and returns it.
The
CallableTaskTest class uses an executor with three threads in its thread pool.
The
ExecutorService.submit() method returns a Future object. Future is an interface that
lets you track the progress of the task that you submit. It is declared as follows:
The
public interface Future<V> {
boolean cancel(boolean mayInterruptIfRunning);
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit) throws InterruptedException,
ExecutionException, TimeoutException;
boolean isCancelled();
boolean isDone();
}
The get() method returns the result of the task execution, which is the same as the returned
value from the call() method of a Callable object. If the task has not yet finished executing,
the get() method blocks. You can use another version of the get() method to specify a
timeout period for waiting for the result of a task execution.
The cancel() method cancels a submitted task. Its call has no effect on a completed task.
It accepts a boolean argument to indicate if the executor should interrupt the task if the task
is still running. If you use cancel(true) to cancel a task, make sure the task responds to the
interruption properly.
The isDone() method tells you if the task has finished executing. It returns true if the task is
finished executing normally, it has been cancelled, or it had an exception during its execution.
In the CallableTaskTest class, you keep the returned Future object in the submittedTask
variable. The Future<Integer> declaration indicates that your task returns an Integer object
as its result.
Future<Integer> submittedTask = exec.submit(task);
Another important method call is the
get() method on submittedTask .
Integer result = submittedTask.get();
I have placed the call to the get() method in a try-catch block because it may throw an
exception. If the task has not finished executing, the get() method will block. The program
prints the result of the task execution, which is the total time that the task spent sleeping
during its execution.
Finally, you shut down the executor using its
shutdown() method.
 
Search WWH ::




Custom Search