Java Reference
In-Depth Information
System.out.println(taskFuture.get());
}
catch(ExecutionException ee)
{
System.err.println("task threw an exception");
System.err.println(ee);
}
catch(InterruptedException ie)
{
System.err.println("interrupted while waiting");
}
executor.shutdownNow();
}
}
Themainthreadthatexecutes Listing6-1 ' s main() methodfirstobtainsanexecutor
by calling Executors ' newFixedThreadPool() method. It then instantiates an
anonymousclassthatimplements Callable andsubmitsthistasktotheexecutor,re-
ceiving a Future instance in response.
Aftersubmittingatask,athreadtypicallydoessomeotherworkuntilitneedstoob-
tainthetask'sresult.Ihavechosentosimulatethisworkbyhavingthemainthreadre-
peatedlyoutputawaitingmessageuntilthe Future instance's isDone() methodre-
turnstrue.(Inarealisticapplication,Iwouldavoidthislooping.)Atthispoint,themain
thread calls the instance's get() method to obtain the result, which is then output.
Caution Itisimportanttoshutdowntheexecutorafteritcompletes;otherwise,the
application might not end. The application accomplishes this task by calling shut-
downNow() .
The callable's call() method calculates e by evaluating the mathematical power
series e = 1/0!+1/1!+1/2!+…. This series can be evaluated by summing 1/ n !, where n
ranges from 0 to infinity.
call() first instantiates java.math.MathContext to encapsulate a precision
(numberofdigits)andaroundingmode.Ichose100asanupperlimitone'sprecision
and HALF_UP as the rounding mode.
Search WWH ::




Custom Search