Java How can i monitor something constantly without 100% CPU load?
Can i just use a while loop in conjunction with wait() and notify()/notifyall() ?
EDIT: I want the else condition of the waitfornextprice method to only execute on the method putPrice occuring.
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 h开发者_运维技巧ere, until putPrice() is called again
while(hasPriceChanged(s)==false) wait();
//Once putPrice has been called, b = getPrice();
b = getPrice(s);
}
return b;
}
Assuming the thing you're trying to monitor is capable of calling notify
/notifyAll
, that's the typical way of doing it, yes.
If it can't notify you, you could poll instead... but a "push" notification with wait
/notify
is preferable.
You can also loop with a small Sleep() in the loop and it will bring your CPU usage from 100% to near 1%. Just add a Sleep(50); in your loop
Why don't you use a java.util.Timer instead of an expensive loop?
There is usually a better way than using wait/notify. Can you explain what you are trying to do and perhaps we can suggest alternatives, e.g. using the concurrency library in Java.
A much better structure is to use event driven processing. When the price changes you want specific actions to occur. You should trigger those actions from a price change.
public void putPrice(String s,int i) {
if (getPrice(s) == i) return;
prices.put(s, i);
List<Runnable> onChange = priceListeners.get(s);
if (onChange==null) return;
for(Runnable run: onChange) run.run();
}
Instead of using Runnable you could create an interface which is notified which key/price changed. This way you can have any number of prices change with just one thread. (Or a small number of threads as you choose)
精彩评论