Java嵌套已同步

时间:2014-05-13 03:34:02

标签: java multithreading synchronized

我有一个问题需要了解嵌套同步的工作原理。 我在这里举两个例子进行比较:

//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次...

1 个答案:

答案 0 :(得分:4)

在这种情况下,内锁不起作用。 Java使用recursive mutexes,因此在给定互斥锁上持有锁的线程可以再次锁定它,并保持锁定计数。只有当退出最后一个synchronized块时,互斥锁才会实际解锁。