title: Update AtomicInteger from other thread
body: <p>I have a class that creates many new objects each on their own thread and I would like to keep a running count across the threads. I wanted to have an <code>AtomicInteger</code> but it's not doing what I expected and instead just gets a smaller version. I'm assuming that this is a race condition error - but I'm not entirely sure.</p>
  
  <p>A created this test example which recreates what I want to do.</p>
  
  <pre><code>public class Test {
  
      public static void main(String args[]) {
          AtomicInteger total = new AtomicInteger(0);
          for (int i = 0; i &lt; 10; i++) {
  
              DoThing doThing = new DoThing();
  
              Thread thread = new Thread(doThing);
              thread.start();
              total.addAndGet(doThing.getTally());
          }
  
          System.out.println(total.get());
      }
  }
  
  class DoThing implements Runnable {
  
      int tally = 0;
      @Override
      public void run() {
  
          for(int i = 0; i&lt; 100; i++) {
              tally++;
          }
  
          System.out.println("Tally is " + tally);
  
      }
  
      public int getTally() {
          return tally;
      }
  }
  </code></pre>
  
  <p>However, this outputs: </p>
  
  <pre><code>Tally is 100
  Tally is 100
  Tally is 100
  Tally is 100
  Tally is 100
  Tally is 100
  Tally is 100
  Tally is 100
  0
  Tally is 100
  Tally is 100
  </code></pre>
  
  <p>When I would like the final output to be 1000. How can I increment across threads?</p>
  
  <p>Thanks in advance.</p>