为什么不能在 Thread 实例中使用 notifyAll()?

Why can't notifyAll() be used in a Thread instance?

我使用的源代码分析器指出不应在 Thread 实例中调用 notifyAll()。我试图向管理层说明这一点,但我想不出一个解释。有人可以帮帮我吗??

顺便说一句,这是继承的代码,所以我不对设计决定负责!

听起来您看到的 SONAR 消息是 this one:

Methods "wait(...)", "notify()" and "notifyAll()" should never be called on Thread instances squid:S2236

Sonar对此有详细的解释:

On a Thread instance, the methods wait(...), notify() and notifyAll() are available only because all classes in Java extend Object and therefore automatically inherit the methods. But there are two very good reasons to not call these methods on a Thread instance:

Doing so is really confusing. What is really expected when calling, for instance, the wait(...) method on a Thread? That the execution of the Thread is suspended, or that acquisition of the object monitor is waited for?

Internally, the JVM relies on these methods to change the state of the Thread (BLOCKED, WAITING, ...), so calling them will corrupt the behavior of the JVM.

同样,advice given in the Java API 是:

It is recommended that applications not use wait, notify, or notifyAll on Thread instances.

内部线程管理是通过锁定线程对象来完成的。如果您自己的应用程序代码锁定在线程上,您可能会遇到意外或令人困惑的行为。例如,当线程终止时,它会向等待它的每个线程发送通知。

在尝试评估问题的可能性时,我会寻找线程可能收到错误通知或由于被用作应用程序代码锁和内部锁而错过通知的情况JVM 代码。 (这看起来可能很乏味。)根据代码,我还会寻找由于锁定线程而不是锁定线程访问的数据结构而导致的可能的一致性问题,并评估锁定方案是否有意义。如果代码是 Thread 的子类,我想检查线程是否被合并以及如何合并。

主要是这条消息会让我想,如果这段代码做了一件坏事,那么它还可能做错了什么? SONAR 消息只是一个提示,表明它在代码中发现了难闻的气味,以便您可以调查并了解问题的严重程度。

您不应该 class 讨论帖。这样做会带来许多众所周知的问题。使用 wait/notifyAll 不是一个很好的选择,因为并发库是十多年前添加的,但在线程上它特别糟糕,因为线程 class 也出于自己的目的使用 wait/notify。