简体   繁体   中英

What's a good, efficient way to implement run()?

Should it just contain a loop like

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; eg

    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 (eg 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} 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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM