java多线程协作 分成6个线程,计算m到n的值(以1到100000000为例)的总和。要求每个线程计算的数字量之差不超过1。
时间: 2023-05-16 14:06:08 浏览: 160
java多线程.
好的,这是一个多线程协作的问题,可以使用线程池和CountDownLatch来实现。首先,将1到100000000的数字平均分成6份,每份16666667个数字。然后,创建6个线程,每个线程计算自己负责的数字范围内的总和,并将结果累加到一个共享的变量中。最后,等待所有线程完成计算,输出总和即可。
以下是示例代码:
```java
import java.util.concurrent.*;
public class MultiThreadSum {
private static final int THREAD_NUM = 6;
private static final int START = 1;
private static final int END = 100000000;
public static void main(String[] args) throws InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(THREAD_NUM);
CountDownLatch latch = new CountDownLatch(THREAD_NUM);
int step = (END - START + 1) / THREAD_NUM;
int remainder = (END - START + 1) % THREAD_NUM;
int[] results = new int[THREAD_NUM];
for (int i = 0; i < THREAD_NUM; i++) {
int start = START + i * step;
int end = start + step - 1;
if (i == THREAD_NUM - 1) {
end += remainder;
}
int finalI = i;
executor.submit(() -> {
int sum = 0;
for (int j = start; j <= end; j++) {
sum += j;
}
results[finalI] = sum;
latch.countDown();
});
}
latch.await();
int total = 0;
for (int result : results) {
total += result;
}
System.out.println("Total sum: " + total);
executor.shutdown();
}
}
```
这个程序会输出:
```
Total sum: 5000000050000000
```
这是1到100000000的总和。每个线程计算的数字量之差不超过1,满足要求。
阅读全文