简体   繁体   中英

Android / java: synchronized object wait and notify

I get confused on the synchronized method. Look at this code below:

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

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

Now, from what I understand, synchronized means only 1 thread can access the code inside. If waitOne() is called by main thread and set() is called by child thread , then (from what I understand) it will create deadlock .

This is because main thread never exit synchronized (monitor) because of while (!signaled) { monitor.wait(); } while (!signaled) { monitor.wait(); } and therefore calling set() from child thread will never able to get into synchronized (monitor) ?

Am I right? Or did I miss something? The full code is in here: What is java's equivalent of ManualResetEvent?

Thanks

When you call wait on an object that you use to synchronize on, it will release the monitor, allowing​ another thread to obtain it. This code will not deadlock.

Have a look at documentation of wait() method.

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.

The key point is the thread releases ownership of monitor and hence you won't get deadlock. Child thread can set the value of signaled and can notify main thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM