我试着调用wait()然后线程失去了锁并且必须重新获得它?这是真的?但很明显,线程不会离开同步块。他正在等待调用wait()的同一行,然后继续前进并且不必重新进入synchronized块?
代码示例:
private int value;
private boolean valueSet = false;
public synchronized int get()
throws InterruptedException {
if (!valueSet) { //should be while here
this.wait();
}
valueSet = false;
this.notifyAll();
return value;
}
public synchronized void put(final int value)
throws InterruptedException {
if (valueSet) { //should be while here
this.wait();
}
this.value = value;
valueSet = true;
this.notifyAll();
}
}
我认为如果一个Thread有锁,那么它只能在synchronized块内吗?