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.
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();
}
}
}
# 1 楼答案
否。请改用^{} ,并确保在包含布尔值的对象上同步。如果不同步且
boolean
不是volatile
,则没有内存障碍,因此无法保证轮询线程将看到对boolean
的更改根据javadoc报告:
因此线程在等待通知时不会占用CPU
下面的代码是一个简单的空闲标志,其中包含一个
waitUntilIdle
方法,您的main
方法可以调用,另一个线程可以调用一个setIdle
方法# 2 楼答案
我同意@Mike Samuel,但我建议您使用concurrent lock packages...
继续mike的范例,用Java5中引入的锁替换他的锁
更具体地说,您可以使用Condition'swait方法——那些需要超时的方法。例如,通过这种方式,您可以每隔一段时间记录一条消息,这条消息将帮助您调试无限等待。如果等待超时