Consider the following program:
class Main extends Thread { public static void main(String[] args) { new Main().start(); }/*from www .ja v a2 s . c o m*/ public void run() { try { System.out.println("Starting to wait"); wait(1000); System.out.println("Done waiting, returning back"); } catch(InterruptedException e) { System.out.println("Caught InterruptedException "); } catch(Exception e) { System.out.println("Caught Exception "); } } }
When executed, this program prints the following:
a) Starting to wait//ww w . j av a 2s. co m Done waiting, returning back b) Starting to wait Caught InterruptedException c) Starting to wait Caught Exception d) After printing "Starting to wait," the program gets into an infinite wait and deadlocks.
c)
The method wait()
is called without acquiring a lock, so the program will result in an IllegalMonitorStateException.
This exception would be caught in the catch block for Exception, hence the output.