B: 1
B: 2
B: 3
B: 4
Done
As the output shows, even though the thread pool contains only two threads, all four tasks
are still executed. However, only two can run at the same time. The others must wait until
one of the pooled threads is available for use.
The call to shutdown( ) is important. If it were not present in the program, then the program
would not terminate because the executor would remain active. To try this for yourself,
simply comment out the call to shutdown( ) and observe the result.
Using Callable and Future
One of the most innovative--and exciting--features of the concurrent API is the new Callable
interface. This interface represents a thread that returns a value. An application can use
Callable objects to compute results that are then returned to the invoking thread. This is a
powerful mechanism because it facilitates the coding of many types of numerical computations
in which partial results are computed simultaneously. It can also be used to run a thread
that returns a status code that indicates the successful completion of the thread.
Callable is a generic interface that is defined like this:
interface Callable<V>
Here, V indicates the type of data returned by the task. Callable defines only one method,
call( ), which is shown here:
V call( ) throws Exception
Inside call( ), you define the task that you want performed. After that task completes, you
return the result. If the result cannot be computed, call( ) must throw an exception.
A Callable task is executed by an ExecutorService, by calling its submit( ) method. There
are three forms of submit( ), but only one is used to execute a Callable. It is shown here:
<T> Future<T> submit(Callable<T> task)
Here, task is the Callable object that will be executed in its own thread. The result is returned
through an object of type Future.
Future is a generic interface that represents the value that will be returned by a Callable
object. Because this value is obtained at some future time, the name Future is appropriate.
Future is defined like this:
interface Future<V>
Here, V specifies the type of the result.
To obtain the returned value, you will call Future's get( ) method, which has these two forms:
V get( )
throws InterruptedException, ExecutionException
V get(long wait, TimeUnit tu)
throws InterruptedException, ExecutionException, TimeoutException
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home