多个atomic类连续调用能否构成原子性?

答案是不能保证,具体可以参考下边案例:

public class MyAtomic {

    AtomicInteger count = new AtomicInteger(0);

    public void test(){
        for(int i=0;i<10000;i++){
            /*此处模拟多个类连续调用:可能出现线程一拿到count为999,线程二拿到count为999,
            这样会造成count进行多次+1,所以输出的结果会大于一千*/
            if(count.get()<1000) {
                count.incrementAndGet();
            }
        }
    }
    public static void main(String args[]){
        MyAtomic myAtomic = new MyAtomic();
        List<Thread> threadList = new ArrayList<>();
        for(int i=0;i<10;i++){
            threadList.add(new Thread(myAtomic::test,"thread-"+i));
        }
        threadList.forEach((o)->o.start());
        threadList.forEach((o)->{
            try {
                o.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        System.out.println(myAtomic.count);
    }

}
posted @ 2019-12-30 10:47  小小吸血鬼  阅读(386)  评论(0编辑  收藏  举报