问题描述
我需要知道wait()和notify()是如何工作的?我无法通过使用wait()和notify()来实现它的工作。相反,如果我使用while()循环进行等待,它可以正常工作。怎么回事?为什么我不能简单地使用wait()和notify()?
I need to know how wait() and notify() works exactly? I couldn't achieve its working by using wait() and notify() as such. Instead if I use a while() loop for wait, it works properly. How is it so? Why can't I use just wait() and notify() simply?
推荐答案
你读过等待 - 功能?
have you read the documentation of the wait-notify functions ?
无论如何,为了实现等待通知机制的最佳方法,使用类似的东西(基于):
anyway, for the best way to achieve a wait-notify mechanism, use something like this (based on this website) :
public class WaitNotifier {
private final Object monitoredObject = new Object();
private boolean wasSignalled = false;
/**
* waits till another thread has called doNotify (or if this thread was interrupted), or don't if was already
* notified before
*/
public void doWait() {
synchronized (monitoredObject) {
while (!wasSignalled) {
try {
monitoredObject.wait();
} catch (final InterruptedException e) {
break;
}
}
wasSignalled = false;
}
}
/**
* notifies the waiting thread . will notify it even if it's not waiting yet
*/
public void doNotify() {
synchronized (monitoredObject) {
wasSignalled = true;
monitoredObject.notify();
}
}
}
做注意事项,该类的每个实例只应使用一次,因此如果需要多次使用它,可能需要更改它。
do note, that each instance of this class should be used only once, so you might want to change it if you need to use it multiple times.
这篇关于如何等待并通知工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!