I am exploring multi threading in Java. I have come across this program to compute primes. Primes are computed in the most inefficient way possible. This is done in purpose to maximize the execution time.
Here is the code
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.*;
import static java.lang.System.exit;
public class Part19_CalculatePrimeNumbersUsingFutureAndCallable {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
List<Future<Integer>> futures = new ArrayList<>();
System.out.println(String.format("The main thread : %s", Thread.currentThread().getName()));
while (true) {
Scanner sc = new Scanner(System.in);
System.out.println("\nI can tell you the nth prime number, Enter n(0 to exit): ");
int n = sc.nextInt();
if (n == 0)
break;
Callable<Integer> primeCalculator = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return calculatePrime(n);
}
};
Future<Integer> primeNumberFuture = executorService.submit(primeCalculator);
futures.add(primeNumberFuture);
}
System.out.println("EXITED");
// check if any of the futures are completed
futures.forEach(f -> {
try {
System.out.println(String.format("\tComputed prime %s", f.get()));
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
});
}
private static int calculatePrime(int n) {
int num = 1, count = 0, i;
while (count < n) {
num = num + 1;
for (i = 2; i <= num; i++) {
// determines the modulo and compare it with 0
if (num % i == 0) {
// breaks the loop if the above condition returns true
break;
}
}
if (i == num) {
// increments the count variable by 1 if the number is prime
count = count + 1;
}
}
return num;
}
}
OUTPUT 1
The main thread : main
I can tell you the nth prime number, Enter n(0 to exit):
0
EXITED
Process finished with exit code 0
This outputs as expected
OUTPUT 2
The main thread : main
I can tell you the nth prime number, Enter n(0 to exit):
1
I can tell you the nth prime number, Enter n(0 to exit):
2
I can tell you the nth prime number, Enter n(0 to exit):
3
I can tell you the nth prime number, Enter n(0 to exit):
0
EXITED
Computed prime 2
Computed prime 3
Computed prime 5
Here the program does not seem to terminate and I cannot understand why.