我的线程中有一个主循环,其中一部分测试空闲 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/