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

  

posted @ 2022-06-23 23:02  活出自己范儿  Views(25)  Comments(0Edit  收藏  举报