Forums Register Login
thread question in k&b's book for 1.5
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!
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.
The following code shows how the main thread can be notified:

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.
What's brown and sticky? ... a stick. Or a tiny ad.
Rocket Oven Kickstarter - from the trailboss

This thread has been viewed 768 times.

All times above are in ranch (not your local) time.
The current ranch time is
Jul 22, 2018 14:39:10.