The implementation of multi-thread synchronization ultimately depends on the lock mechanism. We can imagine that a shared resource is a room and everyone is a thread. When a wants to enter the room, he must get the door lock. Once a gets the door lock, he will immediately lock the door after entering, so B, c, d... you have to wait outside the door until a releases the lock, B, c, d... one of them grabbed the lock (the specific method depends on the implementation of JVM, You can first come, first served, or randomly selected), then entered the room and locked the door. In this way, at most one person can be in the House (using shared resources) at any time ).
Java language specifications have built-in support for multithreading. For Java programs, each object instance has a "Lock". Once a thread acquires the lock, if other threads want to obtain the lock, they can only wait for the thread to release the lock. There is only one way to obtain the lock, that is, the synchronized keyword. For example:
Public class sharedresource {
Private int COUNT = 0;
Public int getcount () {return count ;}
PublicSynchronizedVoid setcount (INT count) {This. Count = count ;}
}
Synchronization Method public synchronized void setcount (INT count) {This. Count = count;} is actually equivalent:
Public void setcount (INT count ){
Synchronized (this) {// obtain this lock here
This. Count = count;
} // Release this lock here
}
The red part indicates the code segment to be synchronized. This area is a "dangerous area". If two or more threads run simultaneously, a conflict occurs. Therefore, you need to change the internal status of sharedresource, you must first obtain the lock of the sharedresource instance.
When the synchronized block is exited, the lock owned by the thread is automatically released, so other threads can obtain the lock again.
To improve performance, you do not have to lock this. For example, sharedresource has two independent variables:
Public class sharedresouce {
Private int A = 0;
Private int B = 0;
Public synchronized void Seta (int A) {This. A = ;}
Public synchronized void SETB (int B) {This. B = B ;}
}
If the entire method is synchronized, SETB () and SETB () cannot be synchronized during Seta (). To improve performance, you can use the locks of different objects:
Public class sharedresouce {
Private int A = 0;
Private int B = 0;
Private object sync_a = new object ();
Private object sync_ B = new object ();
Public void Seta (int ){
Synchronized (sync_a ){
This. A =;
}
}
Public synchronized void SETB (int B ){
Synchronized (sync_ B ){
This. B = B;
}
}
}