Description of volatile variables in Java documents

Here http://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html mention

Can anyone provide an example?

This first gives me the impression that the thread reading volatile variables will synchronize with the writer thread and wait for the write to complete But this is clearly not the case

An example can help a lot, and I appreciate it very much

Thank you, Mustafa

Solution

Suppose you have the following courses:

public class Shared {
    public int a;
    public int b;
    public volatile int c;
}

Now let's say that thread a has a reference to an instance of this class

shared.a = 1;
shared.b = 2;
shared.c = 3;

Let's say that thread B has a reference to the same instance

display(c);
display(b);
display(a);

Then, if the value displayed for C is 3 (that is, if a write of thread a occurs before reading thread b), the JAVA memory model ensures that 2 and 1 will also be displayed as B and a respectively, because all actions of thread a that have been performed before writing volatile C ensure that the thread reading the new value of C is visible

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>