1. Java's inter-thread communication is controlled by the Java Memory Model (JMM).
JMM (Java memory Management) defines the abstract relationship between threads and main memory, one is main memory (shared between multiple threads), and one is the private memory of each thread
2. Why do I need a synchronization mechanism?
(1) Synchronization mechanism generally occurs in multi-threading, when it is necessary to maintain the correctness of the program across threads, when it is necessary to share non-final variables between multiple threads, the synchronization mechanism must be used to ensure that one thread's operation is visible to another thread
(2) The synchronization mechanism ensures reliable communication between multiple threads, guaranteeing mutually exclusive access to shared variables among multiple threads, and synchronizing commonly used keywords are synchronized and volatile
3. Synchronous and asynchronous
Synchronization: When synchronizing data, the server cannot do anything else. For example, when a client mentions a synchronization request, the server cannot perform other operations while synchronizing the data
Async: After a client has raised an asynchronous request, the server can still perform other operations when synchronizing data asynchronously
In Java, synchronization often means synchronizing shared data, or an object or synchronizing a method
4. Volatile keyword
(1) After the member variable is volatile, each time the thread accesses the member variable, it needs to get the object from the shared memory first, and if the member variable changes, it must also be written back to memory
(2) that is, volatile guarantees the member variable read-write mutex, equivalent to a read-write lock
Idea: Volatile does not guarantee the atomicity of multi-threaded operations, it can only keep the data that gets from memory every time it is current
For example, thread A, thread B also gets a member variable from memory to a public volatile static int count=5, and a, B, while manipulating count = count+1, A writes count=6 into the count=6, and the last memory changes The amount will only be count=6.
That is, volatile is simply a lock between the thread and memory, comparing whether the member variables are changed before and after the threads are executed, without controlling the mutex between the threads.
5. Synchronized keyword: Ensure that only one thread at a time executes synchronized-decorated content
(1) Synchronized method
Public synchronized void Test () { //method data}
(2) Synchronized block
Public void Test () { synchronized(obj) { // code block, each time only one thread can access }}
Although the general synchronization will introduce synchronized and volatile, but the individual feel volatile some chicken, can use volatile can be replaced with synchronized. And it's easy to mislead people into trying to be atomic.
java--synchronization mechanism (synchronized, volatile)