我正在解决 Leetcode 问题 1114。我正在使用 wait() 和 notify() 概念。使用 wait() 给出时间限制超过但使用 notifyAll() 给出正确答案。
为什么使用 notify() 给出 TLE 而使用 notifyAll() 它工作正常??
class Foo {
private boolean oneDone;
private boolean twoDone;
public Foo() {
oneDone = false;
twoDone = false;
}
public synchronized void first(Runnable printFirst) throws InterruptedException {
printFirst.run();
oneDone = true;
//notify();
notifyAll();
}
public synchronized void second(Runnable printSecond) throws InterruptedException {
while (!oneDone) {
wait();
}
printSecond.run();
twoDone = true;
//notify();
notifyAll();
}
public synchronized void third(Runnable printThird) throws InterruptedException {
while (!twoDone) {
wait();
}
printThird.run();
}
}
为什么 notify() 给出 TLE 但 notifyAll() 不给出 TLE?
notifyAll()
唤醒所有在此对象监视器上等待的线程。线程通过调用其中一种等待方法在对象的监视器上等待。在当前线程放弃对该对象的锁定之前,被唤醒的线程将无法继续。
notify()
用于仅唤醒一个随机选择的等待对象的线程,然后该线程开始执行。如果不是下一个线程,这个随机选择的线程将放弃锁并回到等待状态,这可能导致死锁。
在代码中使用
notify()
会导致线程错过信号并返回等待状态,如果等待线程没有在超时期限内唤醒,这会导致 TLE。
使用
notifyAll()
唤醒所有等待线程,消除丢失信号和潜在死锁的可能性,让您的代码正常运行。