Java Thread sleep

We might need to pause the execution of a thread for specific time or indefinite time. We have an inbuild option to accomplish this which is sleep method from Thread class, the following methods are available to pause the threads execution.

Thread sleep Example

								
import java.util.Date;

public class SleepOfThread extends Thread {

	public static void main(String[] args) {
		Thread thread=new SleepOfThread ();
		thread.start();
	}
	
	public void run()
	{
		System.out.println("Thread going for a sleep"+new Date());
		try {
			sleep(10000L);//sleeping for 10seconds
		} catch (InterruptedException e) {
			
			e.printStackTrace();
		}
		System.out.println("Thread After a sleep"+new Date());

	}

}

In the above example, we see thread is going for a sleep of 10seconds. After 10seconds, we see thread started execution.

Apart from the sleep we handled InterruptedException as well to handle necessary cleanups in case interrupt method of a thread invoked.