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