我正在考虑这个代码:
public class SharedVariable<T> {
private T value;
public SharedVariable(T init){
this.value = init;
}
public synchronized void testAndSet(Predicate<? super T> p, T value)
throws InterruptedException{
while (!p.test(this.value)){
this.wait();
this.value = value;
}
this.notifyAll();
}
}
有可能用.notify();
代替.notifyAll()
吗?会出现问题吗?
这取决于您希望如何管理锁。notify()
只唤醒一个线程调度程序选择的线程。如果有两个以上的线程共享资源,notifyAll()
唤醒所有的线程,其中一个获得锁。
从技术上讲,如果代码简单,替换它是没有问题的。