aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes thread question in k&b's book for 1.5 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 question in k&b Watch "thread question in k&b New topic
Author

thread question in k&b's book for 1.5

Anna Chu
Ranch Hand

Joined: May 18, 2006
Posts: 30
The 9th question in chapter 9 self test:
1. public class WaitTest {
2. public static void main(String [] args) {
3. System.out.print("1 ");
4. synchronized(args){
5. System.out.print("2 ");
6. try {
7. args.wait();
8. }
9. catch(InterruptedException e){}
10. }
11. System.out.print("3 ");
12. } }
Question: what is the result of trying to compile and run this program?
Answer: 1 2; because there will be no return from the wait call since no other thread will notify the main thread, so "3" will never be printed.

My question is: "3" will not be printed because no thread in this program will notify the main thread. Or it is because generally the main thread can not be notified by other thread.
Thanks a lot!
Surendra Kumar
Ranch Hand

Joined: Jul 04, 2006
Posts: 235
Your first reason is correct.

Any thread can be notified.

Here the thread is waiting on the lock of the object args.
But no other thread is notifying the release of the lock on this object.
Paul Anilprem
Enthuware Software Support
Ranch Hand

Joined: Sep 23, 2000
Posts: 3324
    
    8
The following code shows how the main thread can be notified:



Enthuware - Best Mock Exams and Questions for Oracle/Sun Java Certifications
Quality Guaranteed - Pass or Full Refund!
Dave Reinhardt
Ranch Hand

Joined: Aug 07, 2006
Posts: 54
If this weren't a contrived example to demonstrate the main thread waiting on another thread, wouldn't you want to do something(read/write) with the args object? I get confused with examples that lock on an object, but I can't see why they are locking on that particular object.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: thread question in k&b's book for 1.5