標籤:
內容:在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;}@Overridepublic 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);}}
Java利用Callable、Future進行並行計算求和