当面临一个大数组时,要加快数组求和的速度,是否可以将大数组分拆成多个小数组,然后让cpu的多个线程一起执行计算,以加快计算的速度?
代码package com.dam.mutiThread.calculateSum;
import java.util.Random;
public class CalculateSum {
//嵌套循环次数,用来增加计算量,更大幅度地体现直接计算和并行计算的区别
private static int cycleTime=10;
public static void main(String[] args) {
//随机生成一个数组
long[] array = getArray(99999999);
System.out.println("直接计算----------------------------------------------------------");
long start = System.currentTimeMillis();
long sum1 = 0;
for (long l : array) {
sum1 += l;
int test = 0;
for (int j = 0; j < cycleTime; j++) {
for (int k = 0; k < cycleTime; k++) {
test++;
}
}
}
System.out.println("结果:" + sum1);
System.out.println("计算时间:" + (System.currentTimeMillis() - start) + "ms");
System.out.println();
System.out.println("并行计算----------------------------------------------------------");
start = System.currentTimeMillis();
long sum2 = new CalculateSum().createThread(4, array);
System.out.println("结果:" + sum2);
System.out.println("计算时间:" + (System.currentTimeMillis() - start) + "ms");
}
private static long[] getArray(int size) {
long[] array = new long[size];
for (int i = 0; i < array.length; i++) {
array[i] = new Random().nextInt(20) - 10;
}
return array;
}
private long createThread(int threadCount, long[] arr) {
long sum = 0;
int memberNumOfGroup = arr.length / threadCount;
int start = 0;
int end = memberNumOfGroup - 1;
SumThread[] threads = new SumThread[threadCount];
//准备线程
for (int i = 0; i < threadCount; i++) {
System.out.println("start:" + start + ",end:" + end);
threads[i] = new SumThread(start, end, arr);
start = end + 1;
if (i == threadCount - 2) {
end = arr.length - 1;
} else {
end += memberNumOfGroup;
}
}
//启动线程
for (int i = 0; i < threadCount; i++) {
threads[i].start();
}
try {
for (int i = 0; i < threadCount; i++) {
//等待多线程计算,获取计算结果
threads[i].join();
sum += threads[i].getResult();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return sum;
}
class SumThread extends Thread {
private long result; //记录当前线程计算的结果
private int start; //开始计算的项
private int end; //项数间隔
private long[] arr;
public SumThread(int start, int end, long[] arr) {
this.start = start;
this.end = end;
this.arr = arr;
}
@Override
public void run() {
this.result = 0;
for (int i = this.start; i <= this.end; i++) {
this.result += this.arr[i];
int test = 0;
for (int j = 0; j < cycleTime; j++) {
for (int k = 0; k < cycleTime; k++) {
test++;
}
}
}
}
public double getResult() {
return result;
}
}
}
结果
在计算时,设置了线程数为4,直接计算和并行计算的运算时间如下:



