java多线程协作 分成6个线程,计算m到n的值(以1到100000000为例)的总和。要求每个线程计算的数字量之差不超过1。并输出结果
时间: 2023-05-16 13:06:16 浏览: 113
多线程处理大数据叠加的问题
好的,这个问题可以回答。以下是一个可能的解决方案:
```java
public class MultiThreadSum {
private static final int THREAD_COUNT = 6;
private static final long START = 1;
private static final long END = 100000000;
public static void main(String[] args) throws InterruptedException {
long[] results = new long[THREAD_COUNT];
Thread[] threads = new Thread[THREAD_COUNT];
for (int i = 0; i < THREAD_COUNT; i++) {
final int index = i;
threads[i] = new Thread(() -> {
long start = START + (END - START) / THREAD_COUNT * index;
long end = START + (END - START) / THREAD_COUNT * (index + 1);
if (index == THREAD_COUNT - 1) {
end = END + 1;
}
long sum = 0;
for (long i1 = start; i1 < end; i1++) {
sum += i1;
}
results[index] = sum;
});
threads[i].start();
}
for (Thread thread : threads) {
thread.join();
}
long total = 0;
for (long result : results) {
total += result;
}
System.out.println("Total sum: " + total);
}
}
```
这个程序创建了6个线程,每个线程计算一部分数字的总和,最后把结果加起来得到总和。每个线程计算的数字量之差不超过1,确保了计算的正确性。
阅读全文