- The
Callable
interface represent a thread that return a value.
interface Callable<V>
, V
represents the type of data returned by the task.
- It defines only one method
call()
.
- A
Callable
task is executed by an ExecutorService
, by calling its submit method.
- This submit method is of the form
<T> Future<T> submit(Callable<T> task)
.
- It returns result through an object of type
Future
.
Future
is a generic interface that represents the value that will be returned by a Callable object.
interface Future<V>
, V
specifies the type of the result.
- To obtain the value, we need to call Future's
get()
method.
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.BiFunction;
import java.util.function.Function;
class Utility{
static Function<Integer,Integer> sum = (Integer stop) ->{
int total = 0;
for(int i=0;i<=stop;i++){
total += i;
}
return total;
};
static Function<Integer,Integer> factorial = (Integer stop) ->{
int fact = 1;
for(int i=2;i<=stop;i++){
fact *= i;
}
return fact;
};
static BiFunction<Double,Double,Double> getHypotenuse = (Double s1, Double s2)-> Math.sqrt(s1*s1 + s2*s2);
}
public class Main {
public static void main(String[] args) {
ExecutorService ex = Executors.newFixedThreadPool(3);
Future<Integer> f1 = ex.submit(()-> Utility.sum.apply(10));
Future<Double> f2 = ex.submit(()-> Utility.getHypotenuse.apply(3.0,4.0));
Future<Integer> f3 = ex.submit(()-> Utility.factorial.apply(5));
try{
System.out.println(f1.get());
System.out.println(f2.get());
System.out.println(f3.get());
} catch (ExecutionException | InterruptedException e) {
throw new RuntimeException(e);
}
ex.shutdown();
System.out.println("DONE");
}
}