Note that there are some explanatory texts on larger screens.

plurals
  1. POjava: Printing odd even numbers using 2 threads
    text
    copied!<p>I am trying to print odd and even numbers using 2 different threads alternately. I was able to achieve it using wait, notify and synchronize block but now i want to evaluate if we can achieve it without using wait, notify and synchronize.</p> <p>Following is the code i have but its not working:</p> <pre><code>public class OddEvenUsingAtomic { AtomicInteger nm = new AtomicInteger(0); AtomicBoolean chk = new AtomicBoolean(true); public static void main(String args[]) { final OddEvenUsingAtomic pc = new OddEvenUsingAtomic(); new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (pc.chk.compareAndSet(true, false)) { System.out.println("Odd: " + pc.nm.incrementAndGet()); } } } }).start(); new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } while (true) { if (pc.chk.compareAndSet(false, true)) { System.out.println("Even: " + pc.nm.incrementAndGet()); } } } }).start(); } </code></pre> <p>}</p> <p>Any ideas?</p> <p>I created another version after suggestions from Bruno which seems to be working better:</p> <pre><code>import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; public class OddEvenUsingAtomic { AtomicInteger nm = new AtomicInteger(0); AtomicBoolean chk = new AtomicBoolean(true); public static void main(String args[]) { final OddEvenUsingAtomic pc = new OddEvenUsingAtomic(); new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (pc.chk.get() == Boolean.TRUE) { System.out.println("Odd: " + pc.nm.incrementAndGet()); pc.chk.compareAndSet(true, false); } } } }).start(); new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } while (true) { if (pc.chk.get() == Boolean.FALSE) { System.out.println("Even: " + pc.nm.incrementAndGet()); pc.chk.compareAndSet(false, true); } } } }).start(); } } </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