java – 字段读取同步和volatile之间的可见性差异

我从SO那里读过以下文章

Difference between synchronization of field reads and volatile

提问者写道

the point of the synchronization is to ensure that the value of
acct.balance that are read by this thread is current and that any
pending writes to the fields of the object in acct.balance are also
written to main memory.

最受欢迎的答案:

You are correct.

请研究这段代码:

public class VolatileTest {

    static/* volatile */boolean done = false;

    public VolatileTest() {
        synchronized (this) {

        }

    }

    public static void main(String[] args) throws Exception {
        Runnable waiter = new Runnable() {
            public void run() {
                while (!done)
                    ;
                System.out.println("Exited loop");

            }
        };
        new Thread(waiter).start();
        Thread.sleep(100); // wait for JIT compilation
        synchronized (VolatileTest.class) {
            done = true;
        }
        System.out.println("done is true ");
    }

}

在我的电脑上,这个程序不会终止.

因此,我认为

>如果我更改volatile变量,我会在另一个线程中看到实际值
对于任何优秀的地方!
>如果我用监视器“A”更改同步部分中的变量,我会
仅在带有监视器“A”的同步部分中查看实际值(例如在另一个线程中)

我对么 ?

解决方法:

>是的,这是正确的,因为可以从变量读取写入值之前发生易失性写入.
>不完全是.可以保证在同一监视器上同步的另一个线程将看到更新的值,因为监视器释放发生在同一监视器由另一个线程获取之前.如果没有获取相同的监视器,其他线程可能会看到更新的值.你的配方中“唯一”太强了:)

上一篇:java – 以两种方式在Android sqlite和sql server(crud操作)中同步


下一篇:Java中的synchronized方法和synchronized块之间有什么区别?