在线程工作的同时,将普通变量刷入主存

问题描述 投票:0回答:0

据我了解,当线程未停止时,

memory.a
应该在工作缓存内存中。 例子:

public class SynchronizedMemory {
    // non-visible
    private int a = 0;
    public SynchronizedMemory(int a) {
        this.a = a;
    }

    private static void test2() throws InterruptedException {
        SynchronizedMemory memory = new SynchronizedMemory(1);
        Object lock = new Object();
        new Thread(() -> {
            System.out.println("thread1 start................");
            while (memory.a != -1) {
                synchronized (lock){

                }
            }
            System.out.println("thread1 stop................");
        },"thread1").start();
        // wait for thread1 to run
        Thread.sleep(1000);
        new Thread(() -> {
            memory.a = -1;
            while (true){

            }
        },"thread2").start();
    }
}

据我了解,当

memory.a
没有停止时,
thread2
的更改值应该在工作缓存内存中。 当我运行上面的代码时,
thread1
退出循环并完成。这意味着当
memory.a
仍在运行时,
thread2
thread2
的更改值已被刷新到主内存。 那么谁能解释一下这种情况?

java synchronized
© www.soinside.com 2019 - 2024. All rights reserved.