Hi javers. I cand undestand one thing about method wait(). Could you explain me it? Here is the code:
Well. Here we have two objects with threads: one object (ThreadA) has main thread and second (ThreadB) has his own thread. In line 9 we call the wait method of object b(ThreadB) and I thought that the thread of that object has to wait. But in fact that main thread (ThreadA) will wait. According to java, expression b.wait() means that we call the method wait of object b. How to understand it? Thanks in advance.
1. The program starts at the static main method of class ThreadA - line 2.
2. It creates a ThreadB object and then start its own thread by calling b.start() - line 4.
3. At this point we have two thread running concurrently, for simplicity let's call them thread A (started from static main method) and thread B (started from b.start - line 4).
4. thread A will continue to line 6, and thread B will start executing the run() method - line 19. Both thread is about to synchronize on the same object - b. Let's say, thread A gets a hold on the b's lock first, so it will continue on line 7 while thread B will be blocked at line 20.
5. So, thread A will execute line 8. Then, (and here is your question), it calls b.wait(). What does it mean? It means thread A will be put in b's waiting list and will be blocked (stop running), until a call to b.notify() (or b.notifyAll()) is made and thread A is picked to be removed from b's waiting list.
6. So, now thread A is being blocked, and it releases the b's lock (wait() causes the object's lock to be released). As a result, thread B, now picks up the lock and continue on line 21 thru 23. At line 24, thread B calls b.notify(), what it does is it removed one thread from b's waiting list (in this case, there is only one thread, thread A), and thread A will become runnable again. To be precise, at line 24, thread B is still holding the lock on object b, so, thread A still can not run. After line 25 - end of synchronized block - the lock on object b is released, and thread A is now able to pick up the lock and continue on line 10.
Now, as an exercise, what would happen if at point 4 above, instead of thread A that gets the lock, thread B gets the lock first? (meaning thread A will have to be blocked at line 6 and thread B will continue at line 21) Hope this helps. [ March 16, 2004: Message edited by: David Hadiprijanto ]
So there I was, trapped in the jungle. And at the last minute, I was saved by this tiny ad:
Free, earth friendly heat - from the CodeRanch trailboss