title: These three threads don't take turns when using Thread.yield()?
body: <p>In an effort to practice my rusty Java, I wanted to try a simple multi-threaded shared data example and I came across something that surprised me.</p>
  
  <p>Basically we have a shared <code>AtomicInteger</code> counter between three threads that each take turns incrementing and printing the counter.</p>
  
  <h2>main</h2>
  
  <pre><code>AtomicInteger counter = new AtomicInteger(0);
  
  CounterThread ct1 = new CounterThread(counter, "A");
  CounterThread ct2 = new CounterThread(counter, "B");
  CounterThread ct3 = new CounterThread(counter, "C");
  
  ct1.start();
  ct2.start();
  ct3.start();
  </code></pre>
  
  <h2>CounterThread</h2>
  
  <pre><code>public class CounterThread extends Thread
  {   
      private AtomicInteger _count;
      private String _id;
  
      public CounterThread(AtomicInteger count, String id)
      {
          _count = count;
          _id = id;
      }
  
      public void run()
      {
          while(_count.get() &lt; 1000)
          {
              System.out.println(_id + ": " + _count.incrementAndGet());
              Thread.yield();
          }
      }
  }
  </code></pre>
  
  <p>I expected that when each thread executed <code>Thread.yield()</code>, that it would give over execution to another thread to increment <code>_count</code> like this:</p>
  
  <pre><code>A: 1
  B: 2
  C: 3
  A: 4
  ...
  </code></pre>
  
  <p>Instead, I got output where <code>A</code> would increment <code>_count</code> 100 times, then pass it off to <code>B</code>. Sometimes all three threads would take turns consistently, but sometimes one thread would dominate for several increments.</p>
  
  <p>Why doesn't <code>Thread.yield()</code> always yield processing over to another thread?</p>