1

在这些 Java 情况下会发生死锁
1-

synchronized(obj) {
   obj.syncMethod(); // the method signature: public synchronized void syncMethod() {...}
}

2-

synchronized(obj) {
  if (condition) 
     throw new Exception(); // deadlock because obj lock is not released?
  // do other stuff
}

谢谢你。

4

3 回答 3

2
  1. 不会发生死锁。您已经持有obj的锁。

  2. 如果抛出异常,则释放锁。请参阅此处的问题:

在同步子句中抛出异常的副作用?

于 2012-04-11T23:03:11.870 回答
1
  1. No deadlock will occur - Java's locks are reentrant, that is, while a thread is holding a lock (in your case on obj) it can enter synchronized blocks requiring the same lock without problem (a synchronized method is synchronized on this, which is obj in your case too).
  2. The lock will be released when the synchronized block is left, no matter whether an exception causes the thread to leave it or not.
于 2012-04-11T23:22:10.027 回答
0

如果您没有在synchronized块中捕获异常,那么您的锁将被释放并且不会发生死锁。有关详细信息,请参见此处

于 2012-04-11T23:03:25.470 回答