Am gonna tell what I understood from the following code. Can anyone tell me if am wrong? 1).At any point of time, main thread and thread b can be in their respective synchronized blocks at the same time (coz even though both the threads have their lock on object b, both are methods of different classes). 2).once the main thread encounters the wait method, it comes out of the synchronized block and then whatever is left in the main method is executed only after it is notified right? It does not go into the synchronized block again right?
1).At any point of time, main thread and thread b can be in their respective synchronized blocks at the same time (coz even though both the threads have their lock on object b, both are methods of different classes).
Don't know what you mean by this, but yes, both can be within the block -- but only one is holding the lock. The wait() method releases the lock, which allows another thread to acquire and enter the sync block.
2).once the main thread encounters the wait method, it comes out of the synchronized block
No. The wait() method releases the lock. This isn't exactly "comes out of the synchronized block".
and then whatever is left in the main method is executed only after it is notified right? It does not go into the synchronized block again right?
When a notification occurs, the wait() method will be woken up.... but it will need to reacquire the locks again before it can return from the wait() method.
Okie, If at any particular point of time only one thread has the lock, then what if thread b enters the run method first and then the main method enters the synchronized block on which the wait method is called next? Then the program will just freeze right? I think am gettin lil confused here. In the above program, is it the case that the main method always enters the synchronized code first and only after that the thread b enters the synchronized block?
If thread b enters first, then the main thread will block at the synchronization block waiting for the lock. Thread b will then do the loop, and sent the notification.
Since the main thread has not called wait yet, then the notification is lost. Once thread b exits the synchronization lock, then the main thread enters and calls the wait method.
So when the main method enters the synchronized block and calls the wait(), since no notification on the object is sent, program will just freeze right?