Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

Chapter 26: The Concurrency Utilities 805


The first form waits for the result indefinitely. The second form allows you to specify a time-
out period inwait.The units ofwaitare passed intu,which is an object of theTimeUnit
enumeration,described later in this chapter.
The following program illustratesCallableandFutureby 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 f;
Future f2;
Future 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 {
int stop;


Sum(int v) { stop = v; }

public Integer call() {
int sum = 0;
for(int i = 1; i <= stop; i++) {
sum += i;
}
Free download pdf