The first form waits for the result indefinitely. The second form allows you to specify a time-
out period in wait. The units of wait are passed in tu, which is an object of the TimeUnit
enumeration, described later in this chapter.
The following program illustrates Callable and Future by creating three tasks that
perform three different computations. The first returns the summation of a value, the
second computes the length of the hypotenuse of a right triangle given the length of
its sides, and the third computes the factorial of a value. All three computations occur
simultaneously.
// An example that uses a Callable.
import java.util.concurrent.*;
class CallableDemo {
public static void main(String args[]) {
ExecutorService es = Executors.newFixedThreadPool(3);
Future<Integer> f;
Future<Double> f2;
Future<Integer> f3;
System.out.println("Starting");
f = es.submit(new Sum(10));
f2 = es.submit(new Hypot(3, 4));
f3 = es.submit(new Factorial(5));
try {
System.out.println(f.get());
System.out.println(f2.get());
System.out.println(f3.get());
} catch (InterruptedException exc) {
System.out.println(exc);
}
catch (ExecutionException exc) {
System.out.println(exc);
}
es.shutdown();
System.out.println("Done");
}
}
// Following are three computational threads.
class Sum implements Callable<Integer> {
int stop;
Sum(int v) { stop = v; }
public Integer call() {
int sum = 0;
for(int i = 1; i <= stop; i++) {
sum += i;
}
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home