Thread synchronization mechanism
Synchronization mechanisms are provided in Java to effectively prevent resource conflicts. The synchronization mechanism uses the Synchronized keyword. 1. Sync Block
The synchronization block is called a critical section, which is established using the Synchronized keyword, and its syntax is as follows:
Synchronized (Object) {
}
The operations of a shared resource are typically placed within a synchronized defined area so that when other threads acquire the lock, they must wait for the lock to be released before they can enter the zone. object is any object, each object has a flag bit, and has two values, 0 and 1, respectively. When a thread runs to a synchronization block, it first checks the flag bit of the object, or 0 states, indicating that another thread is running in the synchronization block. This is the thread in the ready state, knowing that the thread in the synchronization block finishes the code in the synchronization block. When the identity bit of the object is set to 1, the thread cannot execute the code in the synchronization block and set the identity bit of the object to 0 to prevent other threads from executing the code in the synchronization block. 2. Sync Method
The synchronization method is the method that modifies the Synchronized keyword before the method, and its syntax is as follows:
synchronized void F () {
}
When an object invokes a synchronization method, the other synchronization methods on that object must wait for the synchronization method to complete before it can be executed.