volatile失效了么?
public class ThreadTest { public static volatile int count = 0; public static AtomicInteger atomicCount = new AtomicInteger(0); public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(new Runnable() { @Override public void run() { int j = 0; while (j < 100000) { Thread threadA = new Thread(() -> { int i = 0; while (i < 100) { count++; atomicCount.incrementAndGet(); i++; } }); threadA.start(); j++; } } }, "thread"); thread.start(); thread.join(); System.out.println("count结果:" + count); System.out.println("atomicCount结果:" + atomicCount.get()); System.out.println("main--stop"); } }
执行结果:
count结果:9999944 atomicCount结果:10000000 main--stop
缘于生活,而归于工作。本人所书,而意于分享。
如有转载,请注明出处!
--活出自己范儿