AtomicInteger

class Atomic{
    private AtomicInteger i = new AtomicInteger(0);
    private int a = 0;

    public static void main(String[] args) throws InterruptedException {
        new Atomic().test();
    }

    public void test() throws InterruptedException {

        ExecutorService executorService = Executors.newFixedThreadPool(5);
        for(int j=1;j<=1000;j++){
            int finalJ = j;
            executorService.execute(()->{
                i.addAndGet(finalJ);
                a=a+finalJ;
            });
        }
        executorService.shutdown();
        while (!executorService.isTerminated()){
            executorService.awaitTermination(5, TimeUnit.SECONDS);
        }
        System.out.println(i);
        System.out.println(a);
    }
}

 

posted @ 2021-01-29 10:11  动力起点  阅读(86)  评论(0编辑  收藏  举报