Header Ads

  • Breaking Now

    Code Snippets: Thread Interruption

    Explain following code snippet:
    class ThreadInterrupted extends Thread {
    public void run() // called when start method executes.
    {
    System.out.println("Inside run");
    try {
    synchronized (this) {
    System.out.println("Before calling wait");
    wait();
    System.out.println("wait is called");
    }
    } catch (InterruptedException ie) {
    System.out.println("value of interrupted():"+interrupted());
    System.out.println("Here goes printStackTrace");
    ie.printStackTrace();
    }
    }
    public static void main(String[] args) {
    ThreadInterrupted threadInterrupted = new ThreadInterrupted();
    threadInterrupted.start(); // control goes to run method.
    System.out.println ("Before calling interrupt()");
    threadInterrupted.interrupt();
    }
    }
    

    Once you execute this snippet of code the output shown at console looks something like:

    Before calling interrupt() Inside run Before calling wait value of interrupted():false Here goes printStackTrace java.lang.InterruptedException at java.lang.Object.wait(Native Method) at java.lang.Object.wait(Unknown Source) at ThreadInterrupted.run (ThreadInterrupted.java:9)

    Explaination:
    Immediately after start() method is called thread is interrupted.When execution goes inside run() method where a synchornised block of code exists it mean only a single instance of this class can access this piece of code which calls wait() method.The current object of current class invokes interrupt() methos which in turn cause InterruptedException.

    1 comment:

    1. Hello,

      Nice to be registered on www.interviewjava.com. My little name is maxizhu ;-)

      ReplyDelete

    Post Top Ad

    Post Bottom Ad