java - 为什么wait()方法可以在没有notify()的情况下工作?

标签 java multithreading reflection wait notify

非常感谢!

我在同步 2 个线程时遇到问题:主线程和从 StepRunner.java 调用的线程。我只需要在下一次迭代开始之前显示迭代结果。

我想要什么:

Please enter step number [1, 2, 3 or 4] or 5 for exit: 2
Please enter natural value for factorial computing: 2
2! = 2
Please enter step number [1, 2, 3 or 4] or 5 for exit:

我不想要什么:

Please enter step number [1, 2, 3 or 4] or 5 for exit: 2
Please enter natural value for factorial computing: 2
Please enter step number [1, 2, 3 or 4] or 5 for exit: 2! = 2

为此,我在 StepRunner.java 中有同步块(synchronized block):

public void run() {
        thread.start();
        synchronized (thread) {
            try {
                while (thread.isAlive()) { /**Loop is an Oracle's recommendation*/
                    thread.wait();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

但是为什么在我的代码的任何地方没有方法 wait() 的情况下方法 wait() 都能正常工作?

最佳答案

Thread's javadoc声明线程完成时在内部调用 Thread.notifyAll():

This implementation uses a loop of this.wait calls conditioned on this.isAlive. As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances.

如您所见,不建议使用此功能,您的代码可以重写如下:

thread.start();
try {
    thread.join();    
} catch (InterruptedException e) {
    e.printStackTrace();
}

鉴于此语句仅出现在 Java 7 javadoc 中,并且建议不要使用此功能,看起来此行为曾经是 Thread 类的实现细节,但人们开始依赖它,因此语言作者必须记录它。

关于java - 为什么wait()方法可以在没有notify()的情况下工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22718849/

相关文章:

c++ - DLL 互斥 - 一个例子

java - 我可以使用 isAssignableFrom 来检查 Java 中 C1 是 C2 的子类型吗?

Java Array 对象返回数组的类型而不是 Array

java - 无法解析 GWT 导入 (gwt-maven-plugin)。

java - 错误 : Package doesn't exists when importing a user defined package

java - 无法在 Scala 中创建嵌套对象

java - 在模拟中移动多辆车的有效方法

java - 如果发生错误,IO 线程向 GUI 线程发出警报

c# - 使用反射比较对象属性

c# - 如何向 Request.Form 集合添加值