Saturday 21 March 2015

Interrupted Exception (Thread.sleep() )

In this post I am going to describe what is an Interrupted Exception is and another thing is why always we write thread.sleep function in try catch block.

A thread or java execution throws an interrupted exception whenever a thread is interrupted by another thread. There might be some other reason also but this is the most frequent reason for the InterruptedException.

Whenever we use Thread.sleep() function, we have to use it in try catch block because this function can throw an interrupted exception. If we will not provide a catch block for handling that exception it might give an error at running time. Because the sleeping thread might be interrupted by some other running thread.

So the code for using thread.sleep will be.

I am writing only main function.
Note: Do not forget to use throws InterruptedException in whichever function you are using Thread.sleep.

public static void main(String [] args) throws InterruptedException{
     try {

           Thread.sleep(1000);  // sleeping the thread for 1000 ms
     } catch( InterruptedException e){

            System.out.println("our thread is interrupted");
        }
  }



No comments:

Post a Comment

Related Posts

Related Posts Plugin for WordPress, Blogger...