Java Thread.sleep() method Example


Thread.sleep method of current thread suspends the execution of a program for a specific time. This method is generally used for giving the execution time to another Thread.

There are two version of sleep method provided.

  1. Thread.sleep(long millis)– specifies the sleep time to the millisecond.
  2. Thread.sleep(long millis, int nanos)– specifies the sleep time to the nanosecond.

Note: sleep() throws InterruptedException exception when another thread interrupts the current thread while sleep is active and IllegalArgumentException – if the value of millis is negative.

SleepMethodExp.java

package org.websparrow.thread.methods;

public class SleepMethodExp extends Thread {
	@Override
	public void run() {
		try {
			for (int i = 1; i <= 10; i++) {
				int var = 2 * i;
				// Pause for 1 seconds
				Thread.sleep(1000);
				System.out.println(var);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		SleepMethodExp sleepMethodExp = new SleepMethodExp();
		sleepMethodExp.run();

	}

}

SleepMethodExp1.java

package org.websparrow.thread.methods;

public class SleepMethodExp1 extends Thread {
	@Override
	public void run() {
		try {
			for (int i = 1; i <= 10; i++) {
				int var = 2 * i;
				// Pause for 1000 millis seconds and 500 nano seconds 
				Thread.sleep(1000, 500);
				System.out.println(var);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		SleepMethodExp1 sleepMethodExp1 = new SleepMethodExp1();
		sleepMethodExp1.run();

	}

}

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.