我有一个 jstack 转储,它似乎表示多个线程已获得对同一对象的锁定。据我了解,这应该是不可能的,但真的是这样吗?
这是在 try block 中进行关键等待调用的代码:
protected boolean waitMaxWaitingTime(UserInfo aUserInfo) throws EventServiceException {
final int theMaxWaitingTime = myConfiguration.getMaxWaitingTime();
if(theMaxWaitingTime <= 0) {
return true;
}
if(aUserInfo.isEventsEmpty()) {
//monitor for event notification and double checked
synchronized(aUserInfo) {
if(aUserInfo.isEventsEmpty()) {
try {
final long theStartTime = System.currentTimeMillis();
// --- THE CRUCIAL WAIT CALL ---
aUserInfo.wait(theMaxWaitingTime);
return (System.currentTimeMillis() - theStartTime >= theMaxWaitingTime);
} catch(InterruptedException e) {
throw new EventServiceException("Error on waiting max. waiting time!", e);
}
}
}
}
return false;
}
这是 jstack 转储(有选择地):
"thread-79" #161 daemon prio=5 os_prio=0 tid=0x000000005d63c000 nid=0x322c in Object.wait() [0x000000007e93c000]
java.lang.Thread.State: TIMED_WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
at de.novanic.eventservice.service.connection.strategy.connector.ConnectionStrategyServerConnectorAdapter.waitMaxWaitingTime(ConnectionStrategyServerConnectorAdapter.java:92)
- locked <0x000000008b8de758> (a de.novanic.eventservice.service.registry.user.UserInfo)
"thread-77" #159 daemon prio=5 os_prio=0 tid=0x000000005d63a800 nid=0x5384 in Object.wait() [0x000000007e83c000]
java.lang.Thread.State: TIMED_WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
at de.novanic.eventservice.service.connection.strategy.connector.ConnectionStrategyServerConnectorAdapter.waitMaxWaitingTime(ConnectionStrategyServerConnectorAdapter.java:92)
- locked <0x000000008b8de758> (a de.novanic.eventservice.service.registry.user.UserInfo)
"thread-74" #156 daemon prio=5 os_prio=0 tid=0x000000006efe6000 nid=0x4828 in Object.wait() [0x000000007e25c000]
java.lang.Thread.State: TIMED_WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
at de.novanic.eventservice.service.connection.strategy.connector.ConnectionStrategyServerConnectorAdapter.waitMaxWaitingTime(ConnectionStrategyServerConnectorAdapter.java:92)
- locked <0x000000008b8de758> (a de.novanic.eventservice.service.registry.user.UserInfo)
如您所见,几个不同的线程(按名称和 tid 线程 ID,在这个线程 thread-79
和 thread-74
中)显然获得了一个锁在同一个 UserInfo 对象 (0x000000008b8de758) 上调用等待。是我弄错了还是有多个线程真正获取了锁并在单个对象上调用了等待?
最佳答案
您的转储显示有多个线程正在等待对象监视器(等待获取它),而不是多个线程(不止一个)已获取它(同时)。前者是完全可能和正常的。后者不可能发生。
换句话说,是的,有几个线程获得了锁/监视器,但这是连续发生的(一个接一个)。一旦一个线程调用 wait,它就会释放锁,然后另一个线程可以获取它(然后再次释放它,依此类推)。
关于java - 多个线程可以等待同一个对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33099220/