I am trying to implement a counter using atomic integer and then printing the final value after all threads finish their tasks , but i am not getting the latest value , in my case the value i should get should be 20 but it is fluctuating like 17,18,16,19,20 etc
the program is as follows:
class AtomicOperations implements Runnable
{
private AtomicInteger ai;
private int a;
AtomicOperations(int aivalue, int ivalue) {
ai = new AtomicInteger(aivalue);
this.a = ivalue;
}
@Override
public void run() {
ai.getAndIncrement();
}
public static void main(String args[]) {
AtomicOperations obj = new AtomicOperations(10, 10);
Thread[] t = new Thread[10];
synchronized (obj) {
for (int i = 0; i < t.length; i++) {
t[i] = new Thread(obj, "Thread-" + (i + 1));
t[i].start();
}
}
System.out.println(obj.ai);
}
}