gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 01:50:27 28 4
gpt4 key购买 nike

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

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

最佳答案

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

Methods "wait(...)", "notify()" and "notifyAll()" should never be called on Thread instancessquid: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 消息只是一个提示,表明它在代码中发现了难闻的气味,以便您可以调查并了解问题的严重程度。

关于java - 为什么不能在 Thread 实例中使用 notifyAll()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35631955/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com