Hello I am Antonio, currently studying for my SCJP certification and currently learning Threads, I have understood the instantiation process as well as the different states Threads can transition to.
However I have been struggling for a few days now with the basic concept of synchronization, wait() and notify(), I have several books and the Java tutorials but can't seem to get the grasp of what wait() does exactly and notify().
It's strange because you command the thread to wait() but it's actually the Thread that issues the command that waits right, also notify, notify who? (and who is waiting) I have seen the producer/consumer model with a stack but even then it's not very clear to me, what I would like to do is code some basic application just telling a thread to wait and another one to respond to notify but I can't get around this.
Antonio, Hi. I found this sample that have an example about wait, notify, notifyAll, i suggest that you get a book on the matter. Concurrency it's very complicated and
hard to make it right, but not imposible
...It's strange because you command the thread to wait() but it's actually the Thread that issues the command that waits right, also notify, notify who?...
Thread that executes the wait() will wait on the particular object it executes the wait() method until some thread executes notify()/notifyAll() on the same instance which will wake up the waiting threads on that particular instance. You can think of this as, every object has a wait list (list of objects which called the wait() method on that particular instance) which are waiting on that instance.
Also look in to the Java Tutorial which explains concurrency from the basics.
Thanks for your early response Angel and Vijitha, I will check the example it simplifies the consumer/producer model.
Vijitha ohhh I see the wait list analogy makes it much more clear, so that's how it is supposed to work right? let me see if I got it right. Thread A needs to have information from Object X but it's not ready so it calls X.wait() entering the wait state itself(Thread A goes to WAITING) then Thread B puts that information and calls X.notify() so that X can let Thread A know that its information is ready, this in turn wakes Thread A.
Something else that has been hard to understand for me is the Deadlock, I understand the concept but not exactly how many objects get involved in a deadlock one needs a key from the other but it's all fuzzy.