Jas*_*son 0 java monitor while-loop wait
我可以将while循环与wait()和notify()/ notifyall()一起使用吗?
编辑:我希望waitfornextprice方法的else条件只对putPrice方法执行.
public synchronized void putPrice(String s,int i) {
if (getPrice(s) != i){
this.Prices.put(s, i);
notify();
}
}
public synchronized int waitForNextPrice(String s) {
int b = null;
if (hasPriceChanged(s)==true){
b = getPrice(s);
}
else{
//Need to block here, until putPrice() is called again
while(hasPriceChanged(s)==false) wait();
//Once putPrice has been called, b = getPrice();
b = getPrice(s);
}
return b;
}
Run Code Online (Sandbox Code Playgroud)
假设你想要监视的东西能够调用notify/ notifyAll,这是典型的做法,是的.
如果它无法通知您,您可以进行轮询......但最好使用wait/ "推送"通知notify.