英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论