Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why is NotifyAll not working??

 
Sunita Vontel
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please see the code below

the output I am getting is
C:\Sunita\java\serv>java B
Hello World!
true
i am in class A is 0
i am in class B is 0
i am in class A is 1
i am in class B is 1
i am in class A is 2
i am in class B is 2
i am in class A is 3
i am in class B is 3
i am in class A is 4
i am in class B is 4
i am in class B is 5
i am in class B is 6
i am in class B is 7
i am in class B is 8
i am in class B is 9
i am in class B i am done with loop
end of B
Can somebody please explain why is the thread A not getting notified??
 
Harry Singh
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Initially I got confused with your code too. You have 2 objects here. Hence you have 2 locks. One object is a and another is B.
When you create 2 threads they will both have different locks. Your thread t1 which executes a wait locks Object A and is waiting for another thread which has a lock on Object A to acquire it and then notify it. Since there is no one else, it keeps on holding the lock and the program just does not terminate. Try running the code by commenting the
if (i == 5)
wait();
it will run fine.
The other thread runs does a notifyAll() which does not notify any one at all ( since no one wants the lock on Object B ).
Hope that helps. That was very insight ful indeed.
 
Harry Singh
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please let me know if it made sense to you.
Thanks
 
Sunita Vontel
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank u Harry.
It cleared my doubt.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic