【问题标题】:wait method wakes up without calling notify(NOT SPURIOUS WAKEUP)等待方法唤醒而不调用 notify(NOT SURIOUS WAKEUP)
【发布时间】:2017-05-19 18:13:32
【问题描述】:

在下面的语句中,wait() 方法被执行,即使没有调用 notify,但语句 below wait() 仅在 laurel 线程完成执行后执行。

我尝试使用其他对象来锁定 hardy 块的同步,这次等待方法仍然永远等待,谁能解释我为什么执行wait() 之后的语句?

package delagation;

public class Solution extends Thread {

    static Thread laurel, hardy;

    public static void main(String[] args) throws InterruptedException {
        laurel = new Thread() {
            public void run() {
                System.out.println("A");
                try {
                    hardy.sleep(1000);
                } catch (Exception e) {
                    System.out.println("B");
                }
                System.out.println("C");
            }
        };
        hardy = new Thread() {
            public void run() {
                System.out.println("D");
                try {
                    synchronized(laurel) {
                        laurel.wait();
                        //wait method is called here, 
                        //There is not notify in this class, 
                        //but the statement below are executing
                        System.out.println(Thread.currentThread().getName());
                    }
                } catch (Exception e) {
                    System.out.println("E");
                }
                System.out.println("F");
            }
        };
        laurel.setName("laurel");
        hardy.setName("hardy");
        laurel.start();
        hardy.start();
    }
}

【问题讨论】:

  • 你希望这段代码能做什么?!当Thread 死亡时,它会调用notifyAll。从不extends Thread。永远不要在Thread 上使用synchronized。除非你真的知道你在做什么......
  • @BoristheSpider 千万不要练习,请打他的脸!
  • 我知道有这个副本,但我找不到。
  • 鲍里斯的所有cmets都在现场。他在三行 cmets 中给出了很多有用的反馈。我真的不明白这如何转化为打脸。

标签: java multithreading synchronized java-threads


【解决方案1】:

您无需假设虚假唤醒来解释这里发生了什么。当 laurel 终止时,它会向等待它的线程发送一个 notifyAll。 (这就是 Thread.join 的工作原理。)

查看 Thread#join 的 api 文档:

此实现使用以 this.isAlive 为条件的 this.wait 调用循环。当线程终止时,将调用 this.notifyAll 方法。建议应用程序不要在 Thread 实例上使用 wait、notify 或 notifyAll。

另外,总是在循环中等待,使用条件;请参阅 Oracle 并发教程,尤其是 Guarded Blocks 页面。 (从描述中你可以看到join waits 在一个循环中,测试条件是isAlive 在加入的线程上,所以这是一个很好的例子。你可以在Thread 类的jdk 源中找到join 方法。)

【讨论】:

  • 你说得对,这不是虚假唤醒。来源?
  • @shmosel:这是可重复的,虚假唤醒是由竞争条件创建的,不应该如此可预测。但为了安全起见,重新措辞。更好?
  • 我不知道不可预测性与 Java 对“虚假唤醒”的定义有关。这是我在 Object 类中找到的定义:线程也可以在没有被通知、中断或超时的情况下唤醒,即所谓的虚假唤醒。
  • @shmosel:不可预测性似乎是竞态条件的典型特征。无论如何,我同意措辞可以改进。我还发现了一个重复的问题。
  • 您已回答并关闭了问题。即使在精神状态良好的情况下完成,我也觉得这值得怀疑。当问题有好的时候关闭它。如果没有给出答案。但不要回答自己,而事后锁定其他答案。尽管如此,您的答案和 dup 都可以。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-31
  • 1970-01-01
  • 2012-03-18
  • 2015-03-10
  • 2021-01-05
相关资源
最近更新 更多