0% found this document useful (0 votes)
7 views1 page

Parallel Array Sum in Java

The document presents a Java program that calculates the sum of an array using a multi-threaded approach with an ExecutorService. It divides the array into chunks and assigns each chunk to a separate thread to compute the sum concurrently. Finally, it aggregates the results from all threads and prints the total sum of the array elements.

Uploaded by

hoangtu112201
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views1 page

Parallel Array Sum in Java

The document presents a Java program that calculates the sum of an array using a multi-threaded approach with an ExecutorService. It divides the array into chunks and assigns each chunk to a separate thread to compute the sum concurrently. Finally, it aggregates the results from all threads and prints the total sum of the array elements.

Uploaded by

hoangtu112201
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

# ArraySumWithExecutor

import [Link].*;
import [Link].*;

public class ArraySumWithExecutor {


// Task to sum a portion of the array
static class SumTask implements Callable<Integer> {
private final int[] array;
private final int start;
private final int end;

public SumTask(int[] array, int start, int end) {


[Link] = array;
[Link] = start;
[Link] = end;
}

@Override
public Integer call() {
int sum = 0;
for (int i = start; i < end; i++) {
sum += array[i];
}
return sum;
}
}

public static void main(String[] args) throws InterruptedException,


ExecutionException {
int[] array = new int[1000];
for (int i = 0; i < [Link]; i++) {
array[i] = i + 1; // Filling array with 1 to 1000
}

int numThreads = 4;
ExecutorService executor = [Link](numThreads);
List<Future<Integer>> futures = new ArrayList<>();

int chunkSize = (int) [Link]([Link] / (double) numThreads);

for (int i = 0; i < numThreads; i++) {


int start = i * chunkSize;
int end = [Link]([Link], start + chunkSize);
[Link]([Link](new SumTask(array, start, end)));
}

int totalSum = 0;
for (Future<Integer> future : futures) {
totalSum += [Link]();
}

[Link]();

[Link]("Total Sum: " + totalSum);


}
}

You might also like