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 AtomicInteger
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.
A created this test example which recreates what I want to do.
public class Test {
public static void main(String args[]) {
AtomicInteger total = new AtomicInteger(0);
for (int i = 0; i < 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< 100; i++) {
tally++;
}
System.out.println("Tally is " + tally);
}
public int getTally() {
return tally;
}
}
However, this outputs:
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
When I would like the final output to be 1000. How can I increment across threads?
Thanks in advance.