java.lang.InterruptedException while interrupt the thread in java


In this Example we are going to understanding the Thread interrupted exceptions with Example.

Error Message :
java.lang.InterruptedException: sleep interrupted
       at java.base/java.lang.Thread.sleep(Native Method)
       at java.base/java.lang.Thread.sleep(Thread.java:340)
       at java.base/java.util.concurrent.TimeUnit.sleep(TimeUnit.java:446)
       at com.si.exceptions.ThreadInterrupt.run(ThreadInterrupt.java:13)

Error Description :

import java.util.concurrent.TimeUnit;

public class ThreadInterrupt extends Thread{
       ThreadInterrupt(){
              super();
       }
       @Override
       public void run() {
              try {
                     TimeUnit.SECONDS.sleep(10);
                     System.out.println("Thread is ready");
              } catch (InterruptedException e) {
                     e.printStackTrace();
              }
       }
}

public class ThreadClass {

       public static void main(String[] args) throws InterruptedException{
             
              ThreadInterrupt t1 = new ThreadInterrupt();
              t1.start();
              t1.interrupt();
       }
}

In the above example ,the red background color line is giving the exception.
When you call the t1.interrupt() method The t1 will interrupt due to sleep() in the run method of ThreadInterrupt class. This will unblock and throw this interrupted exception.

Solution:

To avoid this exception we can use the interrupt method like redbackground color.

package com.si.exceptions;

public class ThreadClass {

       public static void main(String[] args) throws InterruptedException{
             
              ThreadInterrupt t1 = new ThreadInterrupt();
              t1.start();
              Thread.currentThread().interrupt();
       }

}
                         
Output:

Thread is ready. This output will appear after 10 seconds.
Share this post :

Post a comment

Please share your valuable feedback and share this article in social media.

 
Support : Ranga Rajesh Kumar
Copyright © 2019. Error Solution - All Rights Reserved
Site Designed by Ranga Rajesh Kumar