Should it just contain a loop like 开发者_StackOverflow
while (true) { ... }
I find it not so efficient as it consumes the CPU so much. I would like my thread to keep on waiting for something but what's the best way to make it wait without consuming so much CPU?
There are many ways to do this efficiently using Object.wait
and Object.notify
(see here), or using various higher level Java concurrency classes such as blocking queues, latches, futures, semaphores or barriers.
===================================================
You are correct that repeatedly testing the condition is a really bad idea; e.g.
while (!condition) {
// really bad idea ... burns CPU cycles.
}
The following is an improvement, but can still be problematic:
while (!condition) {
Thread.sleep(...); // bad idea
}
The problem is that if you set the sleep interval short, the loop gets expensive. But if you set it longer (e.g. a second or so), then the thread can take up to that amount of time to respond to the condition becoming true. The net result can be reduced throughput and / or sluggish user interfaces.
Sometimes the loop{test; sleep}
approach is the best available option, unfortunately, but if you can avoid it, you should.
Don't do while(true) {}
. If you are waiting for some event, do wait()-notify()
mechanism. Otherwise, use sleep(nsecs)
.
Rather than wait for something, it sounds like you could use the Observer pattern. The Observer maintains a list of it's dependents, called Observables, and notifies them of any changes, usually by calling one of the Observer methods.
Here's how you would code an Observer class and an Observable class.
/** The Observer normally maintains a view on the data */
class MyView implements Observer {
/** For now, we just print the fact that we got notified. */
public void update(Observable obs, Object x) {
System.out.println("update(" + obs + "," + x + ");");
}
}
/** The Observable normally maintains the data */
class MyModel extends Observable {
public void changeSomething() {
// Notify observers of change
setChanged();
notifyObservers();
}
}
精彩评论