再入在同步方法中

huangapple go评论69阅读模式
英文:

Reentrancy in synchronized methods

问题

同步方法可重入吗

我有这段代码:

public class Main {
    
    synchronized void m1() {
        //一些代码
        m2();
        //一些代码
    }
    
    synchronized void m2(){
        //一些代码
    }    
}

假设有两个线程(线程A和线程B)同时尝试访问m1()线程A首先获取了。经过一段时间后,线程A调用了m2(),该方法也在相同的对象上同步。

由于我不想进行任何猜测,可以有人告诉我:当线程A调用m2()时会发生什么吗?我的意思是,一旦线程A调用了m2(),它是否会完全“释放锁”?因为从技术上讲,它离开了方法的框架,那么它是否也会释放锁?

[编辑]:线程A每次调用m2()时是否都会运行它?或者它会释放,以便线程A线程B都可以争夺它们的目标?

英文:

Are synchronized methods reentrant?

I have this code:

public class Main {
    
    synchronized void m1() {
        //some code
        m2();
        //some code
    }
    
    synchronized void m2(){
        //some code
    }    
    
}

Say two threads (Thread A and Thread B) try to access m1() at the same time. Thread A takes lock first. After some time Thread A calls m2(), which is also synchronized on same object.

As I don't want to make any guesses can someone tell me this: Is there any guarantee what will happen when Thread A calls m2()? I mean once Thread A calls m2(), does it 'leave lock' at all? Because technically it left method's frame, so will it leave lock as well?

[EDIT]: Does Thread A get to run m2() every time once it calls it? Or does it leave lock so both Thread A and Thread B would race for their goals?

答案1

得分: 4

在Java中,锁是可重入的。如果线程A持有锁,那么它可以开始执行方法m1。最终它会调用方法m2,因为线程A已经持有锁,所以它不需要再次获取锁来执行方法m2。在内部,锁会保持所有者字段来跟踪这一点。即使锁已经被持有,由于调用m2的是锁的所有者,所以访问是被允许的。这种设计策略可以防止死锁。

英文:

In Java locks are reentrant. If Thread A holds the lock, then it can start executing method m1. Eventually it will invoke method m2, since Thread A already holds the lock, it does not have to reacquire the lock again to execute method m2. Internally the lock keeps the owner field to track this. Even if the lock is already held, since the caller of m2 is the owner of the lock, the access is granted. This design strategy prevents deadlocks.

huangapple
  • 本文由 发表于 2020年10月10日 15:46:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/64291188.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定