java - 等待 - 通知工作?

标签 java multithreading

这是我编写的代码,用于测试 wait()notify() 的工作。 现在我有很多疑问。

class A extends Thread {
  public void run() {
    try {
      wait();
      for (int i = 1; i <= 5; i++) {
        System.out.println(i);
        sleep(500);
      }
    } catch (Exception e) {
    }
    System.out.println("End Of Thread");
  }
}

class ThreadWaitNotify {
  public static void main(String args[]) {
    try {
      A t = new A();
      t.start();
      t.wait();
      t.notify();
      t.join();
      System.out.println("End Of Main");
    } catch (Exception e) {
    }
  }
}

我的问题是:

  1. 当我在main中编写t.wait()时,main不会进一步执行, 我无法进一步恢复它。如何做到这一点?
  2. 其次,我也在线程中编写了wait(), 由于它只打印“线程结束”,而不是循环?即使我 notify() 来自 main 或不...
  3. 现在,如果我在 main 中编写 notify() ,它不会完成执行。 在注释该行时,它完成执行并打印“End Of Main”。

最佳答案

My questions are:

When I write t.wait() in main, the main does not execute further, and I am not able to resume it further. How to do that?

运行 main 的线程在调用 t.wait() 时不会持有 t 上的锁。正如您将从 wait() 的 JavaDoc 中看到的那样:

Throws: IllegalMonitorStateException - if the current thread is not the owner of the object's monitor.

因此,您对 wait() 的调用将导致抛出 IllegalMonitorStateException。您的空 catch block 只是丢弃错误,这使得调试变得困难。 您可以使用 ex.printStackTrace() 显示错误;或者您可以将其作为未经检查的异常重新抛出:

    throw new RuntimeException(ex);

要修复 wait() 调用,您需要在 t 上进行同步:

synchronized (t) {
    t.wait();
}

当您调用notify()时,您还需要持有相同的锁。

Secondly I have written wait() in thread also, due to which it only prints "End Of Thread", not the loop? Even if I notify() from main or not...

同样的事情在这里发生,但在不同的线程中。您创建的新线程不拥有 t 上的锁,因此 wait() 调用会引发异常。同样,您由于没有正确处理异常而丢弃了该异常。

Now if I write notify() in main it does not complete execution. While on commenting that line it finishes execution and prints "End Of Main".

我假设你的意思是“注释掉对wait()和notify()的调用”。这是预料之中的。 run() 方法已经完成,也就是说:它捕获了抛出的 IllegalMonitorStateException 并继续到方法的末尾。 join() 方法在线程执行完毕后返回。这几乎立即发生,因为 wait() 调用立即引发异常。

关于java - 等待 - 通知工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13398666/

相关文章:

c# - 如何在线程之间传递数据?

c++ - 如何从 win32 进程获取线程句柄列表?

java - 确保一个线程先于其他线程完成

Java - 在对象列表和哈希表之间建立关系?

java - 你能以编程方式使用 spark-shell 吗

java - Jackson 的 JSON : Unrecognized field, 未标记为可忽略

java - 如何在 java 中使用 boolean 值对 ArrayLists 进行排序?

java - 我在滥用/误用 Java 反射吗?

java - 多核系统中最终收集线程安全吗?

linux - mkdir() 怎么会成功却设置了错误的权限呢?