Java AtomicInteger increment in 1000 threads does not generate 1000 value

I am executing java code, where I have it AtomicInteger, on which 1000 threads are trying to execute incrementAndGet(). I expected the final value to be 1000. But each run generates 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 cannot understand the mistake I am making here or in my understanding.

+4
source share
2 answers

From https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html#shutdown ()

, , . , . . awaitTermination .

, atomicInt.get(), , AtomicInteger.

+3

, .

executor.awaitTermination(10, TimeUnit.SECONDS) shutdown(), -, .

+8

Source: https://habr.com/ru/post/1688009/


All Articles