Monitor Lock

Monitor Lock (Monitor Lock) is a mechanism for synchronization and mutual exclusion control in Java, also known as internal lock or monitor. Every object has a corresponding monitor lock in Java.

When it encounters synchronizeda code block or method, it acquires the monitor lock of the synchronized object. Only one thread can hold a monitor lock on an object at a time. Other threads trying to acquire the same lock will be blocked until the lock is released.

synchronizedA monitor lock ensures that only one thread can execute the code block or method associated with the lock . It provides mutual exclusion, which prevents multiple threads from accessing shared resources at the same time, which may cause data corruption or inconsistency.

The following is an example to illustrate the use of monitor locks:

public class MyClass {
    private int count = 0;
    
    public synchronized void increment() {
        // 同步方法
        // 同一时间只有一个线程可以执行这个方法
        count++;
    }
}

In the above code, methods synchronizedare decorated with keywords increment. The monitor lock associated with this method is to ensure that only one thread can manipulate variables thiswhen executing the method , and maintain the consistency of shared resources.incrementcount

It should be noted that the monitor lock is reentrant, that is, the same thread can acquire the same lock multiple times without deadlock. A reentrant lock allows a thread to enter a synchronized code block or method as many times as it already holds the lock.

In short, monitor lock is the basic concept of thread synchronization in Java, which provides synchronization and mutual exclusion control. It ensures that only one thread can execute the synchronization code associated with a particular lock object, preventing concurrent access to shared resources, and ensuring thread-safe operations.

Guess you like

Origin blog.csdn.net/qq_39208536/article/details/131473677