Java multithread visibility, atomicity, orderliness and problems

Visibility:

Our data is stored in the main memory of our JMM. If there are multiple threads coming in to access at the same time, then multiple threads of us do not directly modify the data in the main memory,
but copy each data to its own working memory, modify it and then put it back into the main memory. At this time, other threads are notified that this is what we call visibility.
JMM: Java memory model An abstract memory model does not really exist.
Insert picture description here

Atomicity:

For example, our simple n++ command is actually four commands in the underlying bytecode file. If volatile is added, our visibility is guaranteed. However, thread t1 is suspended when executing step 7, and thread t2 modifies the value, then t1 directly writes the data to the memory as soon as it gets the CPU scheduling right. If atomicity is not guaranteed, write loss will occur. So we must ensure visibility in the case of multithreading, atomicity
AtomicInteger atomicInteger = new AtomicInteger(); This is an Integer type that guarantees atomicity
Insert picture description here

Orderliness:

When the computer is executing the program, in order to improve performance, the commands of the program we wrote will be rearranged in the optimal way.
Source code —> Compiler optimized rearrangement —> Parallel instruction rearrangement —> Memory system Rearrangement—>The final executed command.
However , the data dependency between instructions must be considered when rearranging, so we must avoid reordering instructions in a multithreaded environment . This is orderly. Our volatile implements optimization that prohibits instruction rearrangement, thus avoiding multithreading. The program appears out of order in the environment
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_36905956/article/details/105837574