gpt4 book ai didi

Java嵌套同步

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:13:59 26 4
gpt4 key购买 nike

我无法理解嵌套同步的工作原理。我这里举两个例子做个对比:

//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 使用 recursive mutexes ,因此在给定互斥锁上持有锁的线程可以再次锁定它,并保持锁定计数。只有当最后一个 synchronized block 退出时,互斥体才会真正解锁。

关于Java嵌套同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23622359/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com