分成6个线程,计算m到n的值(以1到100000000为例)的总和。要求使用Executors框架,每个线程计算的数字量之差不超过1。给出实现原理
时间: 2024-05-14 13:12:28 浏览: 16
实现原理:
1. 首先确定要计算的总区间[m, n],以及需要分成的线程数。
2. 计算每个线程需要计算的区间范围,即每个线程需要计算的起始值和结束值。
3. 使用Executors框架创建一个FixedThreadPool,线程数为6。
4. 使用for循环创建6个Callable对象,每个Callable对象负责计算一个线程的区间范围内的总和。
5. 将6个Callable对象放入一个List中,然后使用invokeAll方法执行这个List中的所有Callable对象。
6. 得到6个线程计算的结果后,对这6个结果进行累加,得到[m,n]区间内的总和。
代码实现:
```java
import java.util.ArrayList;
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 SumThread implements Callable<Long> {
private long start;
private long end;
public SumThread(long start, long end) {
this.start = start;
this.end = end;
}
@Override
public Long call() throws Exception {
long sum = 0;
for (long i = start; i <= end; i++) {
sum += i;
}
return sum;
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
long m = 1;
long n = 100000000;
int threadNum = 6;
long step = (n - m + 1) / threadNum; // 每个线程需要计算的数字个数
ExecutorService executorService = Executors.newFixedThreadPool(threadNum);
List<Callable<Long>> callableList = new ArrayList<>();
for (int i = 1; i <= threadNum; i++) {
long start = m + (i - 1) * step;
long end;
if (i == threadNum) {
end = n;
} else {
end = start + step - 1;
}
callableList.add(new SumThread(start, end));
}
List<Future<Long>> futureList = executorService.invokeAll(callableList);
long totalSum = 0;
for (Future<Long> future : futureList) {
totalSum += future.get();
}
System.out.println("总和为:" + totalSum);
executorService.shutdown();
}
}
```
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)