最近在学高并发的一些知识,在学到Atomic时,运行程序,与预期不一样
代码如下
public class Learn13 { AtomicInteger count = new AtomicInteger(0); void m() { for(int i= 0; i< 10000; i++) count.getAndIncrement(); } public static void main(String[] args) { final Learn12 learn = new Learn12(); Runnable r = new Runnable() { @Override public void run() { learn.m(); } }; List<Thread> threads = new ArrayList<Thread>(); for(int i= 0; i< 10; i++) { threads.add(new Thread(r, "thead" + i)); } for(Thread thread : threads) { thread.start(); } for(Thread thread : threads) { try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(learn.count); } }
示例将这样可以得到100000的结果,但我没得到,每次不一样,方法不是原子性操作,不知哪里有问题,希望有看到的能帮忙解答下