title: 3 threads to print alternate values in sequence
body: <p>I am trying to create an implementation where multiple threads print alternate values of sequence. So here thread1 will print 1,4,7 thread2 will print 2,5,8 thread3 will print 3,6,9. I am using Atomic integer and modulo function.</p>
  
  <p>Below implementation works fine in the sense that first thread prints 1,4,7 while second prints 2,5,8 and third prints 3,6,9 but problem is that sequence is not maintained i.e output can be like 1,3,2,4,5,7,8,6,9 while i want sequence to be maintained as proper threads shld print those values.
  One condition is i don't want to use synchronize. [Just for learning purpose]</p>
  
  <pre><code>import java.util.concurrent.atomic.AtomicInteger;
  
  public class ThreeThreadsOrderedLockLess {
  
      AtomicInteger sharedOutput = new AtomicInteger(0);
  
      public static void main(String args[]) {
  
  
  
          ThreeThreadsOrderedLockLess t = new ThreeThreadsOrderedLockLess();
  
  
  
          ThreadTasks t1 = t.new ThreadTasks(0);
          ThreadTasks t2 = t.new ThreadTasks(1);
          ThreadTasks t3 = t.new ThreadTasks(2);
  
          Thread ts1 = new Thread(t1);
          Thread ts2 = new Thread(t2);
          Thread ts3 = new Thread(t3);
          ts1.start();
          ts2.start();
          ts3.start();
  
      }
  
      private class ThreadTasks implements Runnable {
  
          private final int threadPosition;
  
  
          public ThreadTasks(int threadPosition) {
              super();
  
              this.threadPosition = threadPosition;
          }
  
          @Override
          public void run() {
  
              while (sharedOutput.get() &lt; 9) {
  
                  if (sharedOutput.get() % 3 == this.threadPosition) {
  
                      System.out.println("Printing output for Thread: "
                              + this.threadPosition + "  "
                              + sharedOutput.incrementAndGet());
                  }
              }
  
          }
      }
  
  }
  </code></pre>