• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

thread's example(about wait and notify) in kathy siera

 
Arjun Srivastava
Ranch Hand
Posts: 432
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


this code works fine
OUTPUT:
waiting for a to be completed
total=45

tell me also about total=45 how?
but in line 17 if we replace "a" with new A()
then it gives IllegalMonitorStateException WHY???




also see this code where a has been replaced with new A() in code 1


then again it gives IllegalMonitorStateException WHY???



 
Ankit Garg
Sheriff
Posts: 9528
33
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The code is simple to understand if you know the wait-notify concept. The reason total becomes 45 is in the for loop in the run method you add i to total. So its like doing 1+2+3+4+5+6+7+8+9 which is 45.

At line 17 if you replace a with new A(), then you'll hold a lock on a different object and call wait on a different object (at line 21). The current thread needs to hold the lock on an object on which you call wait or notify...

(PS: as per the new objectives on Oracle's website, wait-notify is not on the exam anymore)
 
Arjun Srivastava
Ranch Hand
Posts: 432
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ankit Garg wrote:
(PS: as per the new objectives on Oracle's website, wait-notify is not on the exam anymore)




thanks for the information ,i do not know about this thing!!


please have a look at code two also.
 
Shanky Sohar
Ranch Hand
Posts: 1051
Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



Remember what happen when we do
a,start();
it will create a new thread that created thread will call the run method when it gets instantiated.
so the lines after line a.start() continue on exceuting because may be run method has not been started till yet.

If you remove a.wait() and also try/catch block,then JVM will not wait for run to get completed and output may be different each time you run the program.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic