多线程操作--AtomicInteger

主函数:
public static void main(String[] args) throws InterruptedException
    {
        final MultiThreadVolatile test = new MultiThreadVolatile();
        ExecutorService executorService = Executors.newFixedThreadPool(150);
        for (int i =0 ; i < 100000; i++){
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    test.increase();
                }
            });
        }

        executorService.shutdown();
        executorService.awaitTermination(100*1000, TimeUnit.DAYS);
        System.out.println(test.getCount());

    }

能正确运行的代码,每次结果都是100000:

public class MultiThreadVolatile {
    private AtomicInteger count  = new AtomicInteger(0);
    public int getCount(){
        return count.get();
    }
    public void increase(){
        count.incrementAndGet();
    }

}

肯定出问题的代码A:

public class MultiThreadVolatile {
    private Integer count  = 0;
    public int getCount(){
        return count;
    }
    public void increase(){
        count++;
    }

}


可能出问题的代码B:

public class MultiThreadVolatile {
    private volatile Integer count  = 0;
    public int getCount(){
        return count;
    }
    public void increase(){
        count++;
    }

}



猜你喜欢

转载自blog.csdn.net/kielin/article/details/76683939