简体   繁体   English

Java线程同步中的通知

[英]Notification in Java thread synchronization

When there are multiple threads in waiting state; 当有多个线程处于等待状态时; and if I call notify() rather than calling notifyAll() Which one is going to be notified among several threads in waiting state? 如果我调用notify()而不是调用notifyAll()处于等待状态的多个线程中将要通知哪个?

That's undefined behavior. 那是未定义的行为。 Anyone could be picked up. 任何人都可以被接走。 From the JavaDoc : JavaDoc

If any threads are waiting on this object, one of them is chosen to be awakened. 如果有任何线程在此对象上等待,则选择其中一个唤醒。 The choice is arbitrary and occurs at the discretion of the implementation. 选择是任意的 ,并且可以根据实现情况进行选择。

And yes, this can lead to thread starvation . 是的,这可能导致线程饥饿

The javadoc says: Javadoc说:

The choice is arbitrary and occurs at the discretion of the implementation. 选择是任意的,并且可以根据实现情况进行选择。

When there are multiple threads in waiting state; 当有多个线程处于等待状态时; and if I call notify() rather than calling notifyAll() Which one is going to be notified among several threads in waiting state? 如果我调用notify()而不是调用notifyAll()处于等待状态的多个线程中将要通知哪个?

Although as has been mentioned, the particular behavior is not defined by the Java spec, I suspect that JDC implementations will take the thread at the front of the WAIT queue for the particular monitor. 尽管已经提到过,Java规范并未定义特定的行为,但我怀疑JDC实现会在特定监视器的WAIT队列的最前面使用线程。 However this should not be relied on. 但是,这不应该依赖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM