49 lines
1.1 KiB
Java
49 lines
1.1 KiB
Java
package parallel;
|
|
|
|
import test.Test;
|
|
|
|
// @ThreadSafe
|
|
public class CollectingResults {
|
|
|
|
public static long sum(int[] nums) throws Exception {
|
|
long total = 0;
|
|
Thread[] threads = new Thread[Test.NUM_THREADS];
|
|
SumCollected[] collected = new SumCollected[Test.NUM_THREADS];
|
|
int size = (int) Math.ceil((double) nums.length / Test.NUM_THREADS);
|
|
for (int i = 0; i < Test.NUM_THREADS; i++) {
|
|
collected[i] = new SumCollected(nums, i * size, (i + 1) * size);
|
|
threads[i] = new Thread(collected[i]);
|
|
threads[i].start();
|
|
}
|
|
for (int i = 0; i < Test.NUM_THREADS; i++) {
|
|
threads[i].join();
|
|
total += collected[i].getPartialSum();
|
|
}
|
|
return total;
|
|
}
|
|
|
|
static class SumCollected implements Runnable {
|
|
private final int[] nums;
|
|
private final int low;
|
|
private final int high;
|
|
private long partialSum;
|
|
|
|
public SumCollected(int[] nums, int low, int high) {
|
|
this.nums = nums;
|
|
this.low = low;
|
|
this.high = Math.min(high, nums.length);
|
|
this.partialSum = 0;
|
|
}
|
|
|
|
public long getPartialSum() {
|
|
return partialSum;
|
|
}
|
|
|
|
public void run() {
|
|
for(int i = low; i < high; i++) {
|
|
partialSum += nums[i];
|
|
}
|
|
}
|
|
}
|
|
}
|