Foreword-strenuously forget to eat, music to forget excellent, do not know the old will.
Description: In Java, a variable modified by the variables, the thread will read the variable at each time the variable is the most value [Note: Do not be misled by this word. Explain in detail later].volatile is easy to be [Misuse], used for [Atomic NatureOperation
Explanation: In the Java Virtual machine running mechanism, the Java thread to run the program, in order to ensure the efficiency of the program run, each thread runs, the virtual opportunity to separate a temporary memory area for this thread, we can call [current thread-specific memory]
The thread will load the variables needed to run the process into the [current thread-specific memory], (for example, thread A needs to perform an operation on the + + of variable A, when online preempted, the variable A is first added to its own [current thread-specific memory], when the thread
When the execution is complete, the current is saved in the [current thread-specific memory], updated to the [Raw MemoryOf.
Problem: If there are two threadsAAndB, at the same time the variable upate operation, then in two thread execution, there may be a situation, two threads into the program, all in their own [current thread-specific memory], the original value of the variable is saved. Then two threads execute
When finished, the update operation of the last thread that executes overwrites the update operation performed by the first thread.----------------The program is out of sync (the bank is taking money to save.)
Solution Ideas
1. At the same time, only one program to perform the update operation----------inefficient-------synchronized
2. When performing the updtae operation, let the thread not from the [current thread-specific memory], instead of reading the variable directly from memory--------more efficient------- volatile
Java Thread-volatile