I. The visibility of shared variables between threads
Visibility: A thread's modification of shared variable values can be seen by other threads in a timely manner.
Shared variables: If a variable has a copy in the working memory of multiple threads, then this variable is a shared variable of several threads.
Java Memory Model: describes the access rules for various variables (thread-shared variables) in Java programs, and
The JVM stores the variables in memory and reads out the underlying details of the variable from memory.
Java memory Model (JVM):
All of the variables are stored in main memory.
Each thread has its own independent working memory, which holds a copy of the variable used by the thread (a copy of the variable in main memory).
All operations of a thread on a shared variable must be made in its own working memory and cannot be read and written directly from the main memory.
Variables in the working memory of other threads cannot be accessed directly between different threads, and the transfer of variable values between threads needs to be done through main memory.
"Principle of shared variable visibility implementation"
Thread 1 changes to shared variables to be seen by thread 2 in a timely manner, must go through the following 2 steps:
Refreshes the shared variables that were updated in working memory 1 into main memory.
Updates the value of the most recent shared variable in main memory to work memory 2.
Ii. Synchronized realization of visibility
Third, volatile realization of visibility
★ Order Reordering
★as-if-serial semantics
★volatile Precautions for use
Iv. comparison of synchronized and volatile
Detail Java multi-threaded support memory visibility