其他分享
首页 > 其他分享> > 多个atomic类连续调用能否构成原子性?

多个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);
    }

}

标签:count,threadList,调用,int,AtomicInteger,原子,atomic,new,public
来源: https://www.cnblogs.com/smallVampire/p/12118480.html