This repository has been archived on 2021-10-31. You can view files and clone it, but cannot push or open issues or pull requests.
PF3/hw2/Ex3/src/parallel/ThreadPoolPrimeCounter.java

57 lines
1.3 KiB
Java
Raw Normal View History

2019-11-10 16:13:34 +00:00
package parallel;
import util.Prime;
import java.util.List;
import util.PrimeCounter;
import java.util.ArrayList;
2019-11-10 23:36:16 +00:00
import java.util.concurrent.*;
2019-11-10 16:13:34 +00:00
public class ThreadPoolPrimeCounter implements PrimeCounter {
private final int numThreads;
public ThreadPoolPrimeCounter(int numThreads) {
this.numThreads = numThreads;
}
public int countPrimes(int[] nums) throws Exception {
2019-11-10 23:36:16 +00:00
final ExecutorService e = Executors.newFixedThreadPool(numThreads);
final int step = (int) Math.ceil((double) nums.length / numThreads);
final List<Future<Integer>> results = new ArrayList<>(numThreads);
for (int i = 0; i < nums.length; i += step) {
results.add(e.submit(new CountPrimes(nums, i, i + step)));
}
2019-11-10 16:13:34 +00:00
2019-11-10 23:36:16 +00:00
e.shutdown();
int count = 0;
for (Future<Integer> result : results) {
count += result.get();
}
2019-11-10 16:13:34 +00:00
return count;
}
private static class CountPrimes implements Callable<Integer> {
private final int[] nums;
private final int low, high;
private CountPrimes(int[] nums, int low, int high) {
this.nums = nums;
this.low = low;
this.high = Math.min(high, nums.length);
}
@Override
public Integer call() throws Exception {
int count = 0;
for (int i = low; i < high; i++) {
if (Prime.isPrime(nums[i])) {
count++;
}
}
return count;
}
}
}