内容:在Java中利用Callable进行带返回结果的线程计算,利用Future表示异步计算的结果,分别计算不同范围的Long求和,类似的思想还能够借鉴到需要大量计算的地方。
public class Sums {
public static class Sum implements Callable<Long> {
private final Long from;
private final Long to;
public Sum(long from, long to) {
this.from = from;
this.to = to;
}
@Override
public Long call() throws Exception {
long ans = 0;
for (long i = from; i <= to; i++)
ans += i;
return ans;
}
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService executor = Executors.newFixedThreadPool(2);
List<Future<Long>> ans = executor.invokeAll(Arrays.asList(
new Sum(0, 1000), new Sum(10000, 100000), new Sum(1000000, 1000000)));
executor.shutdown();
long sum = 0;
for (Future<Long> i : ans) {
long tmp = i.get();
System.out.println(tmp);
sum += tmp;
}
System.out.println("sum : " + sum);
}
}