gurpeet singh wrote:please consider the following code from kb6 book page no. 748-749 .
in this code we have two threads viz ThreadA and ThreadB. ThreadA has synchronized block on object b. ThreadB has synchronized block on object this , which is same as b. that means if ThreadA enters its synchronized block, it will acquire lock on object b, which means ThreadB will not be able to enter into its run() method. if i'm right ,then what is the need of wait method in ThreadA. because main thread will enter the synchronized block and will get lock on b. hence threadB won't run until main thread releases the lock . which means the output should be :
waiting for b to complete
0 // default value of b will be printed.
But when i run this code it gives me output
Waiting for b to complete...
Total is: 4950
Please explain?
Second part of my question is that, even if i remove the notify() call, still the output does not change. so what is the use of notfiy() method. logically if we remove notify method , ThreadA which is waiting to be notified, will not get notification and hence will not acquire the lock again(which it has released on the call to wait()). which further means that ThreadA should not run and hence should not print total. but reverse happens. why ?
Take a look at the JavaDoc for the wait() method....
http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#wait%28%29
You will noticed that the lock is released.
As for the second part, this issue seems to comes up often, mainly because there are a few mock questions that synchronize on the Thread object.
You should do a bit of searching about it.
Anyway, the reason this is happening is due to implementation detail. The Thread class join() method is implemented via calls to check if the thread is alive and calling wait() on the Thread instance if it is not. When a thread terminates, part of the cleanup is to unset the alive flag and call notifyAll() on the thread object.
So... in your example, your thread object is terminating, and hence, sending a notification to all threads waiting on the Thread object.
Henry