Pausing Execution with Sleep

Thread.sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system. The sleep method can also be used for pacing, as shown in the example that follows, and waiting for another thread with duties that are understood to have time requirements. Example :

public class SleepExample {
	public static void main(String[] args) throws InterruptedException {
		for (int i = 0; i < 5; i++) {
			System.out.println("Main thread, I = " + i);
			Thread.sleep(500); // Thread.sleep(time in milliseconds to sleep
								// thread) is the syntax
		}
	}
}

Creating multiple threads with sleep

when we are creating multiple threads then if one thread goes to other thread and when that thread will go to sleep for some time then the control gets back to the other thread and so on, depending on the number of threads used in program. Example is as follows:

public class example2 implements Runnable {

	Thread t;

	example2() {
		t = new Thread(this, "Second thread");
		System.out.println("Second Thread " + t);
		t.start();
	}

	public void run() {
		for (int i = 3; i > 0; i--) {
			System.out.println("Second  Thread" + i);
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				System.out.println(e);
			}
		}
		System.out.println("Exit Second  thread");
	}

	public static void main(String[] args) throws InterruptedException {
		new example2();
		for (int i = 2; i > 0; i--) {
			System.out.println("Main Thread " + i); // printing default main
													// thread
			Thread.sleep(100);
		}

		System.out.println("Main Thread closed");
	}
}