Saturday, January 22, 2011

Example for thread in java

                 This example illustrates how to create a thread and how to implement the thread. In this example we will see that the program prints numbers from 1 to 10 line by line after 5 seconds which has been declared in the sleep function of the thread class. Sleep function contains the sleeping time in millisecond and in this program sleep function has contained 5000 millisecond mean 5 second time. There is sleep function must caught by the InterruptedException. So, this program used the InterruptedException which tells something the user if thread is failed or interrupted.

Here is the code of the program : 
 
public class Threads{
  public static void main(String args[]){
    Thread th = new Thread();
    System.out.println("Numbers are printing line by line after 5 seconds : ");
    try{
      for(int i = 1;i <= 10;i++)
      {
        System.out.println(i);
        th.sleep(5000);
      }
    }
    catch(InterruptedException e){
      System.out.println("Thread interrupted!");
      e.printStackTrace();
    }
  }
}
 

No comments:

Post a Comment