Incrementing AtomicInteger in Java in 1000 threads does not generate value 1000 [duplicate]

ぃ、小莉子 提交于 2020-01-21 07:51:08

问题


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


回答1:


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

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. Invocation has no additional effect if already shut down. This method does not wait for previously submitted tasks to complete execution. Use awaitTermination to do that.

That means that when you call atomicInt.get() not all threads have been executed and some had no chance of incrementing the AtomicInteger.




回答2:


You're not waiting for the threads to finish before printing out the number.

Add a executor.awaitTermination(10, TimeUnit.SECONDS) after shutdown() and you might see something that you expected.



来源:https://stackoverflow.com/questions/46889706/incrementing-atomicinteger-in-java-in-1000-threads-does-not-generate-value-1000

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!