Java Programming - Threads - Discussion

Discussion Forum : Threads - Finding the output (Q.No. 9)
9.
What will be the output of the program?
public class WaitTest 
{
    public static void main(String [] args) 
    {
        System.out.print("1 ");
        synchronized(args)
        {
            System.out.print("2 ");
            try 
            {
                    args.wait(); /* Line 11 */
            }
            catch(InterruptedException e){ }
        }
        System.out.print("3 ");
    }
}
It fails to compile because the IllegalMonitorStateException of wait() is not dealt with in line 11.
1 2 3
1 3
1 2
Answer: Option
Explanation:

1 and 2 will be printed, but there will be no return from the wait call because no other thread will notify the main thread, so 3 will never be printed. The program is essentially frozen at line 11.

A is incorrect; IllegalMonitorStateException is an unchecked exception so it doesn't have to be dealt with explicitly.

B and C are incorrect; 3 will never be printed, since this program will never terminate because it will wait forever.

Discussion:
6 comments Page 1 of 1.

Nikhil said:   2 years ago
Synchronized (this) is a normally we seen in program right.

But the thing is "this" keyword is nothing but pointing to an object and we know wait (), notify () and notify all () are methods of the object, and String args[] is also object, now we call args. Wait () so until this statement will not end, the next statement will never invoke because no one will notify to waiting thread and that's is why it will not printing 3.

Meet said:   4 years ago
Due to wait method is called, the thread is in wait state till we notify it. So that compiler does not compile remaining code and prints "1 2".

Jjj said:   8 years ago
Me too why synchronized (args) was executed? It seems like a method declaration but it was never called. Is it automatically called?

Vasu said:   8 years ago
If I put which statement the 3 will be print?

Kumaresh said:   9 years ago
I don't understand the term-synchronized (args).

Please someone help me out.

Yamini said:   1 decade ago
There is wait()method is called so progrm will in waiting state.. so 1 and 2 will print and 3 will never print..

Post your comments here:

Your comments will be displayed after verification.