• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

thread question in k&b's book for 1.5

 
Anna Chu
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 236
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3715
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following code shows how the main thread can be notified:

 
Dave Reinhardt
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic