非常感谢!
我在同步 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/