aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes thread's example(about wait and notify) in kathy siera Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "thread Watch "thread New topic
Author

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

Arjun Srivastava
Ranch Hand

Joined: Jun 23, 2010
Posts: 432



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???




SCJP 6 | FB : Java Certifications-Help. | India Against Corruption
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9305
    
  17

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)


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Arjun Srivastava
Ranch Hand

Joined: Jun 23, 2010
Posts: 432

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

Joined: Mar 17, 2010
Posts: 1051




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.


SCJP6.0,My blog Ranchers from Delhi
 
Consider Paul's rocket mass heater.
 
subject: thread's example(about wait and notify) in kathy siera