63 lines
1.3 KiB
Java
63 lines
1.3 KiB
Java
package parallel;
|
|
|
|
import util.Prime;
|
|
import util.PrimeCounter;
|
|
import java.util.concurrent.ForkJoinPool;
|
|
import java.util.concurrent.RecursiveTask;
|
|
|
|
public class ForkJoinPoolPrimeCounter implements PrimeCounter {
|
|
|
|
private static final int SEQUENTIAL_THRESHOLD = 1000;
|
|
private final int numThreads;
|
|
|
|
public ForkJoinPoolPrimeCounter(int numThreads) {
|
|
this.numThreads = numThreads;
|
|
}
|
|
|
|
public int countPrimes(int[] nums) {
|
|
int count = 0;
|
|
// TODO: Complete method countPrimes
|
|
|
|
return count;
|
|
}
|
|
|
|
private static class CountPrimes extends RecursiveTask<Integer> {
|
|
|
|
private final int low, high;
|
|
private final int[] nums;
|
|
|
|
public CountPrimes(int[] nums, int low, int high) {
|
|
this.nums = nums;
|
|
this.low = low;
|
|
this.high = high;
|
|
}
|
|
|
|
@Override
|
|
protected Integer compute() {
|
|
if (low > high) {
|
|
return 0;
|
|
}
|
|
if ((high - low) <= SEQUENTIAL_THRESHOLD) {
|
|
int count = 0;
|
|
for (int i = low; i <= high; i++) {
|
|
if (Prime.isPrime(nums[i])) {
|
|
count++;
|
|
}
|
|
}
|
|
return count;
|
|
}
|
|
else {
|
|
int right, left, rightAns, leftAns;
|
|
right = left = rightAns = leftAns = 0;
|
|
right = low + ((int) Math.floor((high - low) / 2 ) - 1);
|
|
left = low + ((int) Math.ceil((high - low) / 2 ));
|
|
// TODO: Complete method compute
|
|
|
|
|
|
|
|
return leftAns + rightAns;
|
|
}
|
|
}
|
|
}
|
|
}
|