简体   繁体   中英

In Java, is it efficient to use Thread.sleep(1) for an idle thread?

I have a main loop in my thread, and part of it tests for if an idle boolean is true. If it is, it will call Thread.sleep(1) upon each iteration of the loop. Is this an efficient way to go about doing this? My goal is for the thread to take minimal CPU usage when idle.

No. Use Object.wait instead and make sure you synchronize on the object containing the boolean. If you don't synchronize and the boolean is not volatile , you have no memory barrier so there is no guarantee that the polling thread will see the change to the boolean .

According to the javadoc :

This method causes the current thread (call it T) to place itself in the wait set for this object and then to relinquish any and all synchronization claims on this object. Thread T becomes disabled for thread scheduling purposes and lies dormant until one of four things happens:

  • Some other thread invokes the notify method for this object and thread T happens to be arbitrarily chosen as the thread to be awakened.
  • Some other thread invokes the notifyAll method for this object.
  • Some other thread interrupts thread T.
  • ...

so the thread will take no CPU while it is waiting to be notified.

The code below is a simple idle flag with a waitUntilIdle method that your main method can call and a setIdle method that can be called by another thread.

public class IdleFlag {
  private boolean idle;

  public void waitUntilIdle() throws InterruptedException {
    synchronized (this) {
      while (true) {
        // If the flag is set, we're done.
        if (this.idle) { break; }
        // Go to sleep until another thread notifies us.
        this.wait();
      }
    }
  }

  public void setIdle() {
    synchronized (this) {
      this.idle = true;
      // Causes all waiters to wake up.
      this.notifyAll();
    }
  }
}

I agree with @Mike Samuel, yet I would like to recommend that you use the concurrent lock packages...

Continue with mike's paradigm just replace his locking with that introduced in Java 5

More specifically you can use Condition's await methods - those that take timeouts. That way you can, for example, log a message every so often - a message which will help you debug infinite waits. You might also want to perform some rollback logic if the await timesout...

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