Android / java: 同步对象等待并通知

Android / java: synchronized object wait and notify

我对同步方法感到困惑。请看下面的代码:

public void waitOne() throws InterruptedException
{
    synchronized (monitor)
    {
        while (!signaled)
        {
           monitor.wait();
        }
    }
}

public void set()
{
    synchronized (monitor)
    {
        signaled = true;
        monitor.notifyAll();
    }
}

现在,据我了解,synchronized 意味着只有 1 个线程可以访问里面的代码。如果waitOne()主线程调用并且set()被[=25=调用]子线程,然后(据我了解)它将创建死锁

这是因为 主线程 永远不会退出 synchronized (monitor) 因为 while (!signaled) { monitor.wait(); } 因此调用 set() 来自子线程将永远无法进入 synchronized (monitor)?

我说的对吗?还是我错过了什么?完整代码在这里:What is java's equivalent of ManualResetEvent?

谢谢

当你在一个你用来同步的对象上调用wait时,它会释放监视器,让另一个线程获得它。这段代码不会死锁。

查看 wait() 方法的文档。

Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

关键是线程释放了监视器的所有权,因此不会出现死锁。子线程可以设置signaled的值并通知主线程