Krivalar Tutorials 
Krivalar Tutorials

Java Multi Threading - sleep() method






Thread - sleep() method

sleep() method is a static method and can be called on Thread class directly to make the current sleep for a specified number of millseconds. If a Thread sleeps, other threads get the time to execute

Example - using Thread sleep method


public class ThreadSleepExample extends Thread{
	String threadName;

	public ThreadSleepExample(String name){
		this.threadName=name;

	}
	public void run(){
		if(threadName.equals("Thread1")){
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		System.out.println("Inside thread: " + threadName);
	}

	public static void main(String a[]) {
		ThreadSleepExample thread1= new ThreadSleepExample("Thread1");
		ThreadSleepExample thread2= new ThreadSleepExample("Thread2");
		ThreadSleepExample thread3= new ThreadSleepExample("Thread3");
		ThreadSleepExample thread4= new ThreadSleepExample("Thread4");

		thread1.start();
		thread2.start();
		thread3.start();
		thread4.start();
	}

}

Thread sleep Example - Outpunt

Output of the above program may very from machine to machine. One possible output is shown below. You can note that Thread 1 paused for 1000 milliseconds and hence other threads started in the time interval. Order of thread execution may vary depending on a number of factors like how busy the CPU is

Inside thread: Thread2
Inside thread: Thread3
Inside thread: Thread4
Inside thread: Thread1