0 votes
in JAVA by
What is the result of the following program?

public static synchronized void main(String[] args) throws  

InterruptedException {  

     Thread f = new Thread();  

      f.start();  

      System.out.print("A");  

      f.wait(1000);  

      System.out.print("B");  

}  

a) It prints A and B with a 1000 seconds delay between them

b) It only prints A and exits

c) It only prints B and exits

d) A will be printed, and then an exception is thrown.

1 Answer

0 votes
by

(d) A will be printed, and then an exception is thrown.

Reason: The InterruptedException is thrown when a thread is waiting, sleeping, or occupied. The output of the above code is shown below:

A
Exception in thread "main" java.lang.IllegalMonitorStateException
	at java.lang.Object.wait(Native Method)
	at com.app.java.B.main(B.java:9)

In the above code, we have created a thread "f," and when started, A will be printed. After that, the thread will wait for 1000 seconds. Now, an exception is thrown instead of printing B. It is because the wait() method must be used inside a synchronized block or try-catch block unless it will throw an exception, as shown above.

Related questions

0 votes
asked Apr 8, 2021 in JAVA by SakshiSharma
0 votes
asked Apr 9, 2021 in JAVA by Robindeniel
...