Java利用Callable、Future进行并行计算求和

内容:在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);
	}
}


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。