简体   繁体   中英

Using wait() without notify() when in synchronized code piece (java)

I wanted to know if it's possible to use wait() on a synchronized piece of code without using notify(), something like this:

wait_on(B):
    synchronized(B.monitor) {
    B.count--
        while (B.count > 0) { /* wait */ }
    }

Thanks in advance

You need notify or notifyAll to awaken the thread from its wait state. In your sample the code would enter the wait and stay there (unless interrupted).

Know the difference between wait, yield, and sleep. Wait needs to be called in a synchronized block, once the wait is entered the lock is released, and the thread stays in that state until notify is called. Yield returns the thread to the ready pool and lets the scheduler decide when to run it again. Sleep means the thread goes dormant for a fixed period of time (and from there it goes to the ready pool).

Make sure you call wait on the same object that you're synchronizing on (here it's B.monitor).

No! Only option is to wait with a timeout, which surely will not help you.

如果将/* wait */更改为对wait()的调用,并且没有人会调用notify()notifyAll() ,那么此线程将永远不会唤醒...

If it is a barrier that you want, you will need to notifyAll your other threads:

wait_on(B) {
    synchronized(B.monitor) {
        B.count--
        while (B.count > 0) {
            B.monitor.wait()
        }
        B.monitor.notifyAll();
    }
}

Regards,

Pierre-Luc

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