I am executing a java code where I have an AtomicInteger
on which 1000 threads are trying to perform an incrementAndGet()
. I was expecting the final value to be 1000. But each run is generating all sorts of different values. The code is as follows :
class task implements Runnable {
AtomicInteger i ;
task(AtomicInteger ai) {i =ai ;}
public void run() { i.incrementAndGet() ; }
}
class jlt {
public static void main(String[] args) throws Exception {
AtomicInteger atomicInt = new AtomicInteger(0);
ExecutorService executor = Executors.newFixedThreadPool(2);
for(int i=1; i<=1000; i++)
executor.submit(new task(atomicInt)) ;
executor.shutdown() ;
System.out.println(atomicInt.get()); // 1000 is expected
}
}
I am not able to figure out the mistake that I am making here or in my understanding