Callable是Java线程使用中提供的一个具有类型参数的泛型接口,通过实现该接口的call(),可以创建一个该返回值的实例。
调用实例需要使用ExecutorService.submit()。
下面的例子中,通过传入一个参数n,生成一个斐波拉契数列,然后将数列的和计算后返回。
package concurrency21;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
class Fib implements Callable<Integer> {
private static int count = 0;
private final int id = count++;
private List<Integer> list;
private int fib(int n) {
if (n < 2)
return 1;
return fib(n - 2) + fib(n - 1);
}
public Fib(int n) {
list = new ArrayList<>(n);
for(int i = 0; i < n; i++) {
list.add(fib(i));
}
}
@Override
public String toString() {
return "#" + id + " : " + list.toString();
}
@Override
public Integer call() throws Exception {
int result = 0;
for(int i : list)
result += i;
return result;
}
}
public class E5 {
public static void main(String[] args) {
ExecutorService eService = Executors.newCachedThreadPool();
List<Future<Integer>> results = new ArrayList<>();
for(int i = 0; i < 5; i++) {
results.add(eService.submit(new Fib(i+8)));
}
for(Future<Integer> fi : results) {
try {
if(fi.isDone())
System.out.println(fi.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}finally {
eService.shutdown();
}
}
}
}