Java Programming - Threads - Discussion

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 ");
    }
}

[A]. It fails to compile because the IllegalMonitorStateException of wait() is not dealt with in line 11.
[B]. 1 2 3
[C]. 1 3
[D]. 1 2

Answer: Option D

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.


Yamini said: (Jan 18, 2012)  
There is wait()method is called so progrm will in waiting state.. so 1 and 2 will print and 3 will never print..

Kumaresh said: (Dec 13, 2013)  
I don't understand the term-synchronized (args).

Please someone help me out.

Vasu said: (May 28, 2015)  
If I put which statement the 3 will be print?

Jjj said: (Sep 12, 2015)  
Me too why synchronized (args) was executed? It seems like a method declaration but it was never called. Is it automatically called?

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.