利用多线程实现加法并行计算

(要不要考虑点个赞!)

前提:数据规模较小的时候,并行计算可能用时更多

利用Callable创建线程,可以返回值。利用future获取返回值。
以下是源码:

-------------------------------------------------------------------
import java.util.Arrays;
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;

public class Sum_Result {
	
	// Java内置异步执行接口 与  Future共同使用
	public static class Sum implements Callable {
		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 result = 0;
			for (long i = from; i < to; i++)
				result += i;

			return result;
		}
	}

	// 普通计算方法
	public static long getSum(long[] array) {
		long result = 0;
		for (int i = 0; i < array.length; i++) {
			result += array[i];
		}
		return result;
	}

	public static void main(String[] args) throws InterruptedException, ExecutionException {

		// 选一个大型数组
		long[] array = new long[90000000];
		for (int i = 0; i < 90000000; i++) {
			array[i] = i;
		}

		//三个线程计算
//		ExecutorService executor = Executors.newFixedThreadPool(3);
//		long start1 = System.currentTimeMillis();
//		List> ans = executor.invokeAll(
//				Arrays.asList(new Sum(0, 30000000), new Sum(30000000, 60000000), new Sum(60000000, 90000000)));
		
		//四个线程计算
//		ExecutorService executor = Executors.newFixedThreadPool(4);
//		long start1 = System.currentTimeMillis();
//		List> ans = executor.invokeAll(
//				Arrays.asList(new Sum(0, 20000000), new Sum(20000000, 50000000), new Sum(50000000, 70000000), new Sum(70000000, 90000000)));
	
		//九个线程计算
		ExecutorService executor = Executors.newFixedThreadPool(9);
		long start1 = System.currentTimeMillis();
		List> ans = executor.invokeAll(
				Arrays.asList(new Sum(0, 10000000), new Sum(10000000, 20000000), new Sum(20000000, 30000000),
						new Sum(30000000, 40000000), new Sum(40000000, 50000000), new Sum(50000000, 60000000),
						new Sum(60000000, 70000000), new Sum(70000000, 80000000), new Sum(80000000, 90000000)));
		
		long sum = 0;
		for (Future i : ans) {
			long tmp = i.get();
			System.out.println("线程 "+i +" 的结果是: "+tmp);
			sum += tmp;
		}
		
		//并行计算
		long end1 = System.currentTimeMillis();
		System.out.println("并行计算耗时:" + (end1 - start1) + " ms");
		System.out.println("并行计算的结果:" + sum);

		//串行计算
		long start2 = System.currentTimeMillis();
		long result2 = getSum(array);
		long end2 = System.currentTimeMillis();
		System.out.println("单独串行计算耗时:" + (end2 - start2) + " ms");
		System.out.println("单独计算的结果:" + result2);

	}
}

---------------------------------------------------------------------------
贴出部分结果图:

三线程

利用多线程实现加法并行计算_第1张图片
------------------------------------------------
四线程

利用多线程实现加法并行计算_第2张图片

---------------------------------------------------
九线程


利用多线程实现加法并行计算_第3张图片

你可能感兴趣的:(多线程)