Java嵌套同步



我有一个问题,了解如何工作的嵌套同步。我在这里举两个例子来做一个比较:

//example 1
public class Account {
    int balance = 1000;
    Object lock = new Object();
    public int getBalance() throws InterruptedException {
        synchronized(lock) {
            // step 1- Thread 1 enter here and sleep
            Thread.sleep(20);
            return balance;
        }
    }
    public void setBalance(int amount) {
        // step 2 - Thread 2 have to wait until thread 1 release the lock.
        synchronized(lock) {
            this.balance = amount;
        }
    }
}

上面的例子清晰而合乎逻辑。
现在看一下示例2:

public class Account {
    int balance = 1000;
    Object lock = new Object();
    public int getBalance() {
        synchronized(lock) {
            // step 1 - Thread 1 enter here and lock the object.
            synchronized(lock) { //same lock 
                //step 2 - Thread 1 can enter here also if the lock is already locked why????
                //...do something...
                return balance;
            }
        }
    }
}


我不明白在例子2中,如果外部锁已经锁定,为什么同一个线程可以进入同一个锁2次…

在这种情况下,内部锁不起任何作用。Java使用递归互斥锁,因此在给定互斥锁上持有锁的线程可以再次锁定它,并保留锁计数。只有当最后一个synchronized块退出时,互斥锁才真正被解锁。

最新更新