简体   繁体   中英

what is the behavior of java after returning to a synchronized block after notify on an object

I know that after we invoked a wait() on an object, the lock of that object will release to permit another thread to give that lock by a synchronized block and invoke notify() . before we entered the synchronized block that we have called wait() method, we acquire the lock and invoke the wait() .

but after wait() the method release the lock.

now my question is after we invoke notify() in another thread, does the thread that is waiting on that object acquire the lock again.

below is a simple code for this:

Object obj = new Object();
        synchronized (obj) {
            try {
                obj.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            afterWait();
        }

is the lock of object acquire when jvm executes afterWait() method or not because it is also in a synchronized block.

In Java, monitors are implemented according to Mess' semantics. It implies that when current thread needs to wait, it releases the monitor and joins the other waiting threads to get the monitor once again. The written example is not safe, as wait should be in a loop with checking some condition to wait again, as Java does not guarantee that thread will be woken up only in the case of notify() or notifyAll() methods. It may work on your development environment but fail on another one. Also, notify() method does not guarantee that thread will wake up and get the lock as it may not get the signal, so it is safe to do notifyAll() to awake all threads waiting for the lock.

I am new to Stack Overflow, so I am not sure if my shared knowledge is straight to the question or no.

From the Javadoc of wait() (emphasis added):

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 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