I want to find all primes from 0 to 1,000,000. For this, I am writing a stupid method:
public static boolean isPrime(int n) { for(int i = 2; i < n; i++) { if (n % i == 0) return false; } return true; }
and it’s good for me and doesn’t need editing . How will I write the following code:
private static ExecutorService executor = Executors.newFixedThreadPool(10); private static AtomicInteger counter = new AtomicInteger(0); private static AtomicInteger numbers = new AtomicInteger(0); public static void main(String args[]) { long start = System.currentTimeMillis(); while (numbers.get() < 1000000) { final int number = numbers.getAndIncrement();
Note the (1) and (2) marked lines. When (1) is turned on, the program runs quickly, but if turned on (2), it runs slower: I get small portions with a long delay:
Ts: 1480489699692 Thread[pool-1-thread-9,5,main]: 350431 is prime! Ts: 1480489699692 Thread[pool-1-thread-6,5,main]: 350411 is prime! Ts: 1480489699692 Thread[pool-1-thread-4,5,main]: 350281 is prime! Ts: 1480489699692 Thread[pool-1-thread-5,5,main]: 350257 is prime! Ts: 1480489699693 Thread[pool-1-thread-7,5,main]: 350447 is prime! Ts: 1480489711996 Thread[pool-1-thread-6,5,main]: 350503 is prime!
And the threads get an equal number :
Ts: 1480489771083 Thread[pool-1-thread-8,5,main]: 384733 is prime! Ts: 1480489712745 Thread[pool-1-thread-6,5,main]: 384733 is prime!
Please explain to me why option (2) is slower and why the threads get the same value for the number, even though the AtomicInteger multithreading is safe?