Reprint Please specify source:http://blog.csdn.net/ns_code/article/details/17288243
The functionality of locking (synchronized synchronization) is not limited to mutex behavior, but there is another important aspect: memory visibility. not only do we want to prevent a thread from using object state while another thread is modifying the state at the same time, but also want to make sure that when a thread modifies the state of the object, other threads can see the change. And thread synchronization is exactly what this can do.
A lock can be used to ensure that a thread can see the execution results of another thread in a predictable way. To ensure that all threads are able to see the latest values of shared variables, you can add the same lock on all threads that perform read or write operations. Example of the guaranteed visibility of the synchronization.
When thread a executes a synchronous block of code, thread B then enters a synchronous block of code that is protected by the same lock, which guarantees that when a lock is released, all the variable values seen by a ( a variable including y and x before the lock is released) can also be seen by B after acquiring the same lock in B. In other words, when thread B executes a lock-protected synchronization code block, you can see all the results of the operation in the same lock-protected synchronization code block before thread A. If thread B enters lock m after threads a unlock m, thread B can see the operation before thread a unlock m, and can get i=1,j=1. If thread A enters lock m after unlock m, thread B does not necessarily see the action in thread A, so the value of J is not necessarily 1.
Public class mutableinteger { privateint value; Public int Get () { return value; } Public void Set (int value) { this. Value = value; } }
In the above code, both the Get and set methods access value without synchronization. if value is shared by multiple threads, if a thread calls set, another thread that is calling get may see the updated value value, or it may not be visible.
By synchronizing the set and get methods, you can make Mutableinteger a thread-safe class, as follows:
Public class synchronizedinteger { privateint value; Public int Get () { return value; } Public void Set (int value) { this. Value = value; } }
The set and get methods are synchronized, with the same object lock, so that the Get method can see the change in the value of the set method, so that the value of values obtained each time through the Get method is the most recent value of value.
Java Concurrency Programming (14) memory visibility of synchronization problems