这种情况下会出现死锁吗?
我是否正确地说,在以下情况下应该会发生死锁:
对象 P 调用对象 A 的同步方法,
调用对象 B 的同步方法,
调用对象A的同步方法。
抱歉,如果我看起来很愚蠢,很可能确实如此。但这就是我问的原因。谢谢!
Am I right in saying that a deadlock is supposed to happen in the following case:
Object P calls a synch method of object A,
that calls a synch method of object B,
that calls a synch method of object A.
Sorry if it looks stupid of me, most probably it is. But that's why I'm asking. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据您提供的信息 - 不,不会发生死锁:
首先,您没有提到多个线程。单个线程不会导致死锁。但我们假设您有多个线程。
因此,如果来自不同线程的任何其他对象以相反的顺序调用其中一些方法,则可能会发生死锁。
这种情况的解释如下:
Thread-1
获得进入methodA
所需的锁,然后尝试进入methodB
。如果同时另一个线程 -Thread-2
调用methodB
并获取其锁,则尝试进入methodA
,但是Thread-1
已经拥有锁,因此Thread-2
等待。但是,Thread-1
无法进入methodB
,因为Thread-2
拥有锁。他们永远等待(僵局)。By the information you give - no, a deadlock can't occur:
First, you don't mention multiple threads. A single thread can't cause a deadlock. But let's assume you have multiple threads.
So, if any other object, from different thread invokes some of these methods in reverse order, then a deadlock can occur.
The explanation of the situation is as follows:
Thread-1
obtains the lock required to entermethodA
, and then tries to entermethodB
. If at the same moment another thread -Thread-2
invokesmethodB
and obtains the lock for it, then tries to entermethodA
, butThread-1
already has the lock, soThread-2
waits. However,Thread-1
can't entermethodB
becauseThread-2
has the lock. And they wait forever (deadlock).不。它是同一个线程,同步方法是可重新输入的。
如果您从维基百科中获取定义:“死锁是一种情况,其中两个或更多相互竞争的操作都在等待另一个完成”。您只有一个操作(线程)。
No. It is same thread, synch methods are reenterable.
If you take definition from wikipedia: "A deadlock is a situation wherein two or more competing actions are each waiting for the other to finish". You have only one action (thread) .
不会,线程已经持有A上的锁,所以不会死锁。线程永远不能与自身争用锁。
No, the thread will already hold the lock on A, so it won't deadlock. A thread can never contend for a lock with itself.