java - 在 Java 中,对空闲线程使用 Thread.sleep(1) 是否有效?

标签 java multithreading sleep

我的线程中有一个主循环,其中一部分测试空闲 boolean 值是否为真。如果是,它将在每次循环迭代时调用 Thread.sleep(1)。这是一种有效的方法吗?我的目标是让线程在空闲时占用最少的 CPU。

最佳答案

没有。使用 Object.wait相反,并确保您在包含 boolean 值的对象上同步。如果您不同步并且 boolean 不是 volatile,您就没有内存屏障,因此无法保证轮询线程会看到对 的更改 boolean 值

根据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.
  • ...

因此线程在等待通知时不会占用 CPU。

下面的代码是一个简单的空闲标志,带有一个main 方法可以调用的waitUntilIdle 方法和一个可以调用的setIdle 方法通过另一个线程。

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

关于java - 在 Java 中,对空闲线程使用 Thread.sleep(1) 是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9705482/

相关文章:

c++ - 'clock_gettime' 和 'gettimeofday' 的奇怪计时结果

java - 在 JPanel Netbeans 上获取单击目标

Java 等待线程完成

C# Getter-Setter 竞争条件

java - 睡在 SwingWorker 里?

c - sleep() 对 c 中静态变量的影响

java - 如何解析来自 Unirest 调用的 JSON 结果

java - 在 spring 中用复选框绑定(bind)类中的 arraylist 的问题

java - 我将数据放入 map 中并以不同的顺序获取它

c++ - 浏览器中的多线程 WebAssembly 比单线程慢,为什么?