AtomicInteger in multithreading
<p>I want to find out all the prime numbers from 0 to 1000000. For that I wrote this stupid method:</p>
<pre class="lang-java prettyprint-override"><code>public static boolean isPrime(int n) {
    for(int i = 2; i &lt; n; i++) {
        if (n % i == 0)
            return false;
    }
    return true;
}
</code></pre>
<p>It's good for me and it <strong>doesn't need any edit</strong>. Than I wrote the following code:</p>
<pre class="lang-java prettyprint-override"><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() &lt; 1000000) {
        final int number = numbers.getAndIncrement();  // (1) - fast
        executor.submit(new Runnable() {
            @Override
            public void run() {
  //               int number = numbers.getAndIncrement(); // (2) - slow
                if (Main.isPrime(number)) {
                    System.out.println(&quot;Ts: &quot; + new Date().getTime() + &quot; &quot; + Thread.currentThread() + &quot;: &quot; + number + &quot; is prime!&quot;);
                    counter.incrementAndGet();
                }
            }
        });
    }
    executor.shutdown();
    try {
        executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        System.out.println(&quot;Primes: &quot; + counter);
        System.out.println(&quot;Delay: &quot; + (System.currentTimeMillis() - start));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code></pre>
<p>Please, pay attention to (1) and (2) marked rows. When (1) is enabled the program runs fast, but when (2) is enabled it works slower.</p>
<p>The output shows small portions with large delay</p>
<pre><code>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!
</code></pre>
<p>and threads get equal <code>number</code> value:</p>
<pre><code> Ts: 1480489771083 Thread[pool-1-thread-8,5,main]: 384733 is prime!
 Ts: 1480489712745 Thread[pool-1-thread-6,5,main]: 384733 is prime!
</code></pre>
<p>Please explain me why option (2) is more slowly and why threads get equal value for number despite AtomicInteger multithreading safe?</p>