# 多线程求和，计算1到100000000（一亿）的和

public class A {

long value = 0;

A(long value){
this.value = value;
}

}//类A用于记录各线程的和

public class MultiSum implements  Runnable{

private  A sum;
private int fromInt;
private int toInt;

public MultiSum(A sum, int fromInt, int toInt, int threadNo) {
this.sum = sum;
this.fromInt = fromInt;
this.toInt = toInt;

}

@Override
public void run() {
long current = System.currentTimeMillis();
for (int i = fromInt; i <= toInt; i++) {
this.sum.value += i;
}
current = System.currentTimeMillis() - current;
+ fromInt + " to " + toInt + " in " + current
+ " milseconds. Sum is " + sum.value);
}

public static void main(String[] args) throws InterruptedException {
Integer toMax = 100000000; //计算1到100000000的和
long sum = 0;
int threads = 6; // 计算线程数
// 每个线程计算一段连续的加和，并将加和结果保存在数组中。
for (int i = 0; i < threads; i++) {
subSum[i] = new A(0);
}
for (int i = 0; i < threads; i++) {
int fromInt = toMax * i / threads + 1; // 边界条件
int toInt = toMax * (i + 1) / threads; // 边界条件
new Thread(new MultiSum(subSum[i], fromInt, toInt, i)).start();
}
for (int i = 0; i < threads; i++) {
sum += subSum[i].value; //异步求和问题
}
System.out.println("The sum is :" + sum);
}

}

https://blog.csdn.net/ghsau/article/details/7451464     Java线程(七)：Callable和Future

https://www.jianshu.com/p/76ceee5657ae   使用CompletionService非阻塞获取多线程返回值

04-03 249

03-23 2万+

10-20 778

03-11 1836

07-28 2080

03-06 401

06-04 345

10-24 1197

#### 【Java多线程实战】求和

©️2020 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。