We can run various computer software programs on computers.
Each running program may contain multiple independent threads ).
A Thread is a program that runs independently and has its own dedicated running stack.
Threads may share resources with other threads, such as memory, files, and databases.
Conflicts may occur when multiple Java threads synchronize locks to read and write the same shared resource at the same time.
At this time, we need to introduce the thread "synchronization" mechanism, that is, there must be a first-in-one between all threads, and we cannot rush together for a group.
Synchronization is translated from synchronize. I don't know why I should use this word that is easy to misunderstand.
Since we all use this, we have to do that. The real meaning of the Java thread synchronization lock is the opposite to that of the word surface.
The real meaning of thread synchronization is actually "Queuing": Several threads need to queue up to operate the shared resources one by one, rather than simultaneously.
Therefore, the first thing to remember about thread synchronization is that thread synchronization is thread queuing. Synchronization means queuing.
The purpose of thread synchronization is to avoid "synchronous" thread execution. This is really a boring tongue twister.
The second point to keep in mind about thread synchronization is the word "sharing.
Only read/write access to shared resources needs to be synchronized. If resources are not shared, there is no need for synchronization.
The third point that needs to be kept in mind for thread synchronization is that only "variables" require synchronous access.
If the shared resources are fixed and unchanged, it is equivalent to a "constant", and the thread does not need to synchronize the read constants at the same time.
At least one Java thread synchronizes the lock to modify shared resources. In this case, synchronization is required between threads.
The fourth point that needs to be firmly remembered about thread synchronization is:
The Code accessed by multiple threads to share resources may be the same code or different code;
Whether or not the same code is executed, as long as the code of these threads accesses the same variable shared resource, these threads need to be synchronized.