The sleep method in threading

The Thread class is having a sleep(long interval) . It makes to sleep the current thread for the specified interval.The interval specified will be minimum time it stays in the sleeping state.We cannot guarantee , when it is returning to running .This method is throwing InterruptedException .So in code we need to handle that also

The sleep method in threading  – Example

Let us see an example . Here we are trying to display numbers from 1 to 10 with an interval of 5 seconds.After printing each number , thread stays in sleeping mode for 5000 ms.

public class SleepSample extends Thread {
public SleepSample() {
}
public void run() {
int number = 0;
while (number < 10) { System.out.println("Number = " + number); try { number++; sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { SleepSample sample = new SleepSample(); sample.start(); } }

The program just prints the numbers with good interval.It is enough to understand the concept.

See Related Discussions

Threading Basics

Thread Safety in Java

Thread Communication in Java

Thread Priorities in Java

The join() method in Threading

The yield() method in Threading

Daemon Threads in Java

Thread pool executor in java

Thread pools in Java

Thread Dead lock in Java

Thread Live lock in Java