【问题标题】:Use of notify() and notifyAll() doesn't work in the code使用 notify() 和 notifyAll() 在代码中不起作用
【发布时间】:2013-07-10 20:46:38
【问题描述】:

我粘贴了下面的代码。这是足够的评论。 清除等待()。当它来到这里时,它会跳到另一个街区。那部分我很橡木。 我的疑问是为什么我们使用 notify 和 notifyAll()。如果你从下面的代码中删除这两个,它工作正常。

class Reader extends Thread{
    Calculator c;
    //here we didn't write no-arg constructor.  Note this.
    // one - arg constructor.
    public Reader(Calculator calc){
        c = calc;
    }
    public void run(){
        synchronized(c){
        // 2. Acquiring the object lock and executes this code of block.
            try{
                System.out.println("Waiting for calculation...");
                c.wait();
                // 3.  Release the object lock and moves to the second synchronize block below
                // 6. Later the object get the lock here and moves on.
            }catch(InterruptedException e){
            }
            System.out.println("Total is: "+c.total);
        }
    }
    public static void main(String[] args){
        //Instantiating new with no-arg.  One more doubt,  How this work without no-arg constructor above.  Please explain.
        Calculator calculator = new Calculator();
        //Instantiating new with one-arg
        new Reader(calculator).start();
        new Reader(calculator).start();
        new Reader(calculator).start();
        // 1. Once you start here it will goto first synchronized code block above
        calculator.start();
    }
}

class Calculator extends Thread{
    int total;

    public void run(){
        synchronized(this){
        // 4. This block acquires that object lock and executes the code block below.

            for(int i=0;i<100;i++){
                total +=i;
            }
            // 5.  As per documentation,  If we give notify() it will release the object lock to only one thread object of its choice.
            //     If we use notifyAll(); it will release the object lock to all the three thread object.
            notify();
            // My doubt here is without using the notify or notifyAll it is working fine.
            // As per docs if we use notify() only one object should get the lock.  That is also not working here.
        }
    }
}

【问题讨论】:

  • 可能是线程实例上的通知/等待行为与其他对象上的不同。 stackoverflow.com/questions/14186828/…
  • 显然是的。没有线程对象实例如何启动线程?
  • 啊,但是同步可以在一个单独的对象上。我认为我的评论解释了为什么您的程序在没有明确的 notify 的情况下运行良好。
  • 除了什么 assylias 和其他:除非你真的想扩展一个线程,否则你不应该继承它。使用 Runnable 创建你的线程。如果您还不熟悉 java 并发,请先阅读优秀教程docs.oracle.com/javase/tutorial/essential/concurrency。使用 Executors 和更高级别的并发类,而不是 synchronize/wait/notify。
  • “我的疑问是没有使用 notify 或 notifyAll 它工作正常”所以“notify() 和 notifyAll() 不起作用”是不正确的,他们似乎没必要?

标签: java multithreading wait notify synchronize


【解决方案1】:

无法保证线程开始运行的顺序。如果计算器首先运行,则其notify 将丢失,并且不会通知任何读者。

【讨论】:

    【解决方案2】:

    一般评论:the javadoc of Object#wait 声明

    与单参数版本一样,中断和虚假唤醒是可能的,并且此方法应始终在循环中使用。

    因此,等待线程可以在没有收到通知的情况下唤醒,您的设计应通过在循环中等待并检查退出条件来考虑这一点(参见 javadoc 中的示例)。


    但是,在您的情况下,问题略有不同。根据Thread#join javadoc:

    当线程终止时,将调用 this.notifyAll 方法。建议应用程序不要在 Thread 实例上使用 wait、notify 或 notifyAll。

    因此,当您的计算器完成时,它会调用 this.notifyAll() 并唤醒所有等待的线程。


    如何解决?

    您应该在计算器中使用一个单独的锁定对象,类似于:private final Object lock = new Object();,并为读者提供一个 getter。

    【讨论】:

      【解决方案3】:

      这是上述程序的更正版本,它对 notify() 和 notifyAll() 有意义。 在这里,我实现了 Runnable 而不是扩展 Threads。那是我所做的唯一改变。它工作得很好。

      class Reader implements Runnable{
          Calculator c;
          public Reader(Calculator calc){
              c = calc;
          }
          public void run(){
              synchronized(c){
                  try{
                      System.out.println("Waiting for calculation...");
                      c.wait();
      
                  }catch(InterruptedException e){
                  }
                  System.out.println("Total is: "+c.total);
              }
          }
          public static void main(String[] args){
      
              Calculator calculator = new Calculator();
      
              Reader read = new Reader(calculator);
      
              Thread thr  = new Thread(read);
              Thread thr1 = new Thread(read);
              Thread thr2 = new Thread(read);
      
              thr.start();
              thr1.start();
              thr2.start();
              new Thread(calculator).start(); 
          }
      }
      class Calculator implements Runnable{
          int total;
          public void run(){
          System.out.println("Entered Calculator");
              synchronized(this){
                  for(int i=0;i<20;i++){
                      total +=i;
                  }
                      notifyAll();
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2016-12-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-21
        • 2021-12-21
        • 2011-02-19
        • 1970-01-01
        相关资源
        最近更新 更多