is this thread Safe? I keep getting different results every time I'm not sure how to make this thread safe. My goal is to compute the amount of primes starting from 5 -10000 but doing this using a thread for each computation. I would like to keep track of the total amount of prime numbers. if I run the code below I get 21 sometimes and 22 sometimes.
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.io.IOException;
public class Main {
private static AtomicInteger count =new AtomicInteger(0);
private static ExecutorService ex = Executors.newFixedThreadPool(100);
public static void main(String []args) throws IOException {
int x =5;
while(x < 90){
final int index =x;
ex.execute(new Runnable(){
public void run(){
synchronized(count){
if(isPrime(index)){
count.incrementAndGet();
}
}
}
});
x++;
//new Thread(task).start();
}
ex.shutdown();
System.out.println(count.get()+ "this how many numbers are prime");
}
public static boolean isPrime(int n)
{
// Corner cases
if (n <= 1)
return false;
if (n <= 3)
return true;
// This is checked so that we can skip
// middle five numbers in below loop
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
}