Master java skills

Thread.sleep() method

Thread.sleep() is a static method of Thread class, which means we have to call it using Thread class name. It is used to make a thread sleep for some amount of time. There are two variants of it:

public static void sleep(long millis) throws InterruptedException   
public static void sleep(long millis, int nanos) throws InterruptedException  

Thread.sleep() with the one parameter is a native method. Native methods are those java methods that start in another language than java. Native methods can access system specific functions and apis that are not directly available in java.

The other method, with two parameters, is not native. We can access sleep() methods with the help of class name. Both methods throw a checked Exception InterruptedException, therefore, whenever we call this method, we have to handle this exception either using try-catch block or adding it in throws clause.

sleep() method parameters

long millis : this is the time in milli seconds for which the thread will sleep.

int nanos : this is the additional time in nano seconds to sleep

Points to remember

  1. sleep() method pauses the execution of currently running thread for the specified time.
  2. If any other thread interrupts, InterruptedException is thrown.

Example

package com.javatrainingschool;

public class RunnableTask implements Runnable {
	
	public void run() {
		for(int i=0; i < 3; i++) {
			System.out.println("Value of i = " + i);
			try {
				Thread.sleep(2000,2);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
package com.javatrainingschool;

public class SleepMethodExample {

	public static void main(String[] args) {
		
		Thread t = new Thread(new RunnableTask());
		t.start();
	}
}
Output :
Value of i = 0
Value of i = 1
Value of i = 2

Causing main method to sleep – example

package com.javatrainingschool;

public class RunnableTask implements Runnable {
	
	public void run() {
		for(int i=0; i < 3; i++) {
			System.out.println(Thread.currentThread().getName() + " : Value of i = " + i);
		}
	}
}
package com.javatrainingschool;

public class SleepMethodExample {

	public static void main(String[] args) {
		
		Thread t1 = new Thread(new RunnableTask());
		Thread t2 = new Thread(new RunnableTask());
		t1.start();
		
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		t2.start();
	}
}
Output :
Thread-0 : Value of i = 0
Thread-0 : Value of i = 1
Thread-0 : Value of i = 2
Thread-1 : Value of i = 0
Thread-1 : Value of i = 1
Thread-1 : Value of i = 2

In the above example, there would be delay of 3000 milliseconds (or 3 seconds) between Thread-0 and Thread-1 statements.