Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The code is not correctly synchronized, that's the problem.</p> <p>The following execution order is allowed in your code:</p> <ol> <li>First thread sees <code>chk == true</code>, sets it to <code>false</code> and enters the <code>if</code> block.</li> <li>Second thread sees <code>chk == false</code>, sets it to <code>true</code> and enters the <code>if</code> block.</li> </ol> <p>Now, you have 2 threads both inside their <code>if</code> blocks, getting ready to:</p> <ol> <li><code>incrementAndGet()</code> the number</li> <li>Print it.</li> </ol> <p>Therefore, you have absolutely no control on what is going to happen.</p> <ul> <li>You can have any of the threads call <code>incrementAndGet()</code>, therefore you can have thread "Odd" printing, first, an odd number, and later, an even number.</li> <li>You can have the first thread print the number, loop, see that the condition is satisfied again (since the second thread has set <code>chk</code> to <code>true</code> again, print, all of this before the second thread had the chance to print).</li> </ul> <p>As you can see, to achieve the result you want, you must have the following operations done atomically:</p> <ul> <li><code>compareAndSet()</code> the boolean</li> <li><code>incrementAndGet()</code> the number</li> <li>print it</li> </ul> <p>If the 3 operations are not atomic, then you can have the threads being scheduled to run the operations in any possible order, you have no control on the output. The easiest way to achieve this is to use a synchronized block:</p> <pre><code>public static void main(final String... args) { final Object o = new Object(); // ... thread 1 ... synchronized(o) { if (boolean is in the expected state) { change boolean, get number, increment, print } } // ... thread 2 ... synchronized(o) { if (boolean is in the expected state) { change boolean, get number, increment, print } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload