1亿求和(java多线程分段实现)
1亿的数据累加求和计算 如果单纯的递归调用那么肯定会出现内存溢出异常
我们可以把数据分段 求每一段的和 最后汇总就行了 这样问题就简单了许多
下面是具体的代码实现:
package com.lq.learn.learn.demo;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
public class demo2 {
//具体的每一段的递归求和计算
public long sum(long start, long n) {
if (n == start) return start;
return sum(start, n - 1) + n;
}
public static void main(String[] args) throws InterruptedException {
demo2 demo = new demo2();
demo.sumFirst(100000000L);
}
public void sumFirst(long n) throws InterruptedException {
//分成i份 这里写死的 当然可以动态添加的
long countOfPer = 100000;
long block = n / countOfPer;
long temp =block;
// 来保存最终的每一段的值
List list = new ArrayList();
long j = 1;
//保存每一段的起始值 和 开始值
List list2 = new ArrayList();
for (long m = 1; m <= countOfPer; m++) {
list2.add(j);
list2.add(temp);
j = temp + 1;
temp = block* (m + 1);
}
CountDownLatch countDownLatch = new CountDownLatch(list2.size() - 1);
for (int h = 1; h < list2.size(); h++) {
//开启多个线程计算
int finalH = h;
new Thread(new Runnable() {
@Override
public void run() {
long realSum = sum((long) list2.get(finalH - 1), (long) list2.get(finalH));
System.out.println(" realsum " + realSum);
// 将值保存到集合 然后计数器-1
list.add(realSum);
countDownLatch.countDown();
}
}).start();
}
countDownLatch.await();
//计算完毕
System.out.println(" success");
}
}