gpt4 book ai didi

Java 对象锁定 : Deadlock when calling other methods?

转载 作者:搜寻专家 更新时间:2023-11-01 01:13:52 25 4
gpt4 key购买 nike

如果我在两个方法中使用 synchronize(this) 并且一个调用另一个,我会陷入死锁情况还是会因为线程已经拥有锁而工作?

想象下面的类:

public class Test {
public void foo() {
synchronize(this) {
bar();
}
}

public void bar() {
synchronize(this) {
// do something
}
}
}

可以看到,有两个方法foo和bar,都依赖同步。

调用foo()时,会在(this)上获得一个锁; bar 在被 foo 调用时会尝试做同样的事情(从而导致死锁)还是它会意识到锁已经被同一个线程获得?

希望我的解释或多或少清楚 ;-)

最佳答案

synchronized block 是可重入的(事实上,Java 监视器是可重入的,非常清楚),因此在您的情况下不会发生死锁。

根据 the docs :

Recall that a thread cannot acquire a lock owned by another thread. But a thread can acquire a lock that it already owns.

关于Java 对象锁定 : Deadlock when calling other methods?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11194014/

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