码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-05-16 01:33:29      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

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


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

标签:

原文地址:http://blog.csdn.net/u011345136/article/details/45752825

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!