标签:ace static mic exce ack rgs inter nts i++
答案是不能保证,具体可以参考下边案例:
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); } }
标签:ace static mic exce ack rgs inter nts i++
原文地址:https://www.cnblogs.com/smallVampire/p/12118480.html