Thread Synchronization in Java
In Java, each object has only one monitor and one mutex, and each monitor can have multiple "Doors" to access.CodeIt can be in different places, because the same object can appear in different code segments, as long as the mutex lock object is the same, each entry is indicated by the synchronized keyword, when a thread passes the synchronized keyword, it holds all the doors of the monitor. Therefore, mutex defines monitor rather than code.
An example is provided to help you understand the concept of monitor:
There is only one restroom in the flying mountain. Many passengers want to go in, but only one person can go in at a time. Others must wait. At this time, there is a corresponding relationship as follows:
Aircraft: Object
Passengers: various threads
Restroom: Monitor
Lock on the bathroom door: mutex
Because synchronization costs are high, avoid the following:
1. There is no need to synchronize atomic operations: one atomic operation will not be interrupted by another thread, so the atomic operation does not need to be synchronized;
2. Avoid synchronization. In terms of language, it means "immutability". The state of an object with immutability will not change after it is created, so the unchanged object does not need to be synchronized; normally, if you frequently access an object without modifying it, the object does not need to be synchronized. A good way is to make the object immutable;
3. Use the synchronous package and use the decoration mode to select between synchronization and non-synchronization.
In addition, the Java specification does not require the wait () method to be implemented as an atomic operation. Therefore, it is better to use the while clause to determine whether the wait () condition is better than the if clause, although the if clause plays a role in some java implementations, its behavior is not clear. The if clause uses the while clause, also known as spin lock, and replaces the if clause with it for the sake of security. (While and if do not understand this too clearly)