一个有10000个元素的整型数组,数组中的每个元素是0-10000间的随机整数,计算数组中所有元素之和,要求用两个线程实现。Java
时间: 2024-10-24 07:10:41 浏览: 8
4-14_lv一维数组中所有元素之和_
在Java中,我们可以使用`ConcurrentHashMap`和`ForkJoinPool`或者`ExecutorService`以及自定义的`ThreadLocal`来实现这个任务的并行计算,确保两个线程同时对数组的一半进行求和。以下是使用`ExecutorService`的一个示例:
```java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ParallelSum {
private int[] array;
private int totalSum = 0;
public ParallelSum(int[] array) {
this.array = array.clone();
}
public void parallelSum(ExecutorService executor) {
int half = array.length / 2;
List<Future<Integer>> futures = new ArrayList<>();
for (int i = 0; i < half; i++) {
final int start = i;
Future<Integer> future = executor.submit(() -> sumSubArray(start, start + half));
futures.add(future);
}
// Wait for all threads to finish and get their results
for (Future<Integer> future : futures) {
totalSum += future.get(); // Block until result is available
}
executor.shutdown();
}
private int sumSubArray(int low, int high) {
int sum = 0;
for (int i = low; i < high; i++) {
sum += array[i];
}
return sum;
}
public int getTotalSum() {
return totalSum;
}
public static void main(String[] args) {
int[] randomArray = new int[10000]; // 随机填充0-10000的整数
// ... (填充随机数)
ExecutorService executor = Executors.newFixedThreadPool(2); // 创建一个固定大小的线程池
ParallelSum sumCalculator = new ParallelSum(randomArray);
sumCalculator.parallelSum(executor);
System.out.println("Total sum: " + sumCalculator.getTotalSum());
}
}
```
在这个例子中,我们首先将数组分成两半,然后创建一个线程池来处理每个部分的求和。当所有任务完成之后,我们将结果合并得到最终总和。
阅读全文