分成6个线程,计算m到n的值(以1到100000000为例)的总和。要求使用Executors框架,每个线程计算的数字量之差不超过1
时间: 2024-04-29 22:21:06 浏览: 174
計算m到n間所有整數的和
以下是Java代码实现:
```java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class SumCalculator {
private static final int THREAD_NUM = 6;
private static final long START_NUM = 1L;
private static final long END_NUM = 100000000L;
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(THREAD_NUM);
long perThreadNum = (END_NUM - START_NUM) / THREAD_NUM;
for (int i = 0; i < THREAD_NUM; i++) {
long start = START_NUM + perThreadNum * i;
long end = i == THREAD_NUM - 1 ? END_NUM : start + perThreadNum - 1;
executorService.execute(new Calculator(start, end));
}
executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.MINUTES);
System.out.println("Total sum: " + Calculator.totalSum);
}
private static class Calculator implements Runnable {
private final long start;
private final long end;
private static long totalSum = 0;
public Calculator(long start, long end) {
this.start = start;
this.end = end;
}
@Override
public void run() {
long sum = 0;
for (long i = start; i <= end; i++) {
sum += i;
}
synchronized (Calculator.class) {
totalSum += sum;
}
}
}
}
```
首先,我们定义了线程数量和计算的起始和结束数。然后,我们通过ExecutorService创建一个固定数量的线程池。
为了使每个线程计算的数字量之差不超过1,我们将总数除以线程数量,然后将其分配给每个线程。如果线程数量不能完全整除总数,则最后一个线程计算的数字范围将略微大于前面的线程。
在每个线程中,我们按顺序计算数字的总和,并使用synchronized关键字将每个线程的总和合并为一个总和。
最后,我们关闭线程池并等待所有线程执行完毕。然后输出总和。
阅读全文