Java Sleeping Thread

Java Sleeping Thread :

We have already learnt about the thread scheduler in the last chapter. In this chapter we will be learning sleeping the thread.

Method Name sleep()
Use of Method Used to sleep a thread for the specified time
Exception Thrown InterruptedException
Parameter Taken Time in milliseconds

Syntax of sleep() :

Thread class provides two methods -

public static void sleep(long miliseconds)
public static void sleep(long miliseconds, int nanos)

Example Program :

package com.c4learn.thread;
public class SleepingThread extends Thread {
   public void run() {
     for (int i = 1; i < 5; i++) {
	try {
	     Thread.sleep(500);
	} catch (InterruptedException e) {
	   System.out.println("Exception !!!");
	}
	System.out.println(i);
     }
  }
   public static void main(String[] args) {
      SleepingThread t1 = new SleepingThread();
      SleepingThread t2 = new SleepingThread();
      t1.start();
      t2.start();
  }
}

Output of the program :

1
1
2
2
3
3
4
4

Explanation of Thread Method :

In the above program we have created two threads -

SleepingThread t1 = new SleepingThread();
SleepingThread t2 = new SleepingThread();

When we start first thread then it will print number “1″ and will take pause for 500 milliseconds.

Thread.sleep(500);

Meanwhile the second thread will start its execution which also prints a number “1″ and again 2nd thread will take pause for 500 milliseconds.

In this way the thread will take rest and resume its execution.