Skip to content

Java Thread Sleep Method Example

Ramesh Fadatare edited this page Aug 29, 2018 · 1 revision

Thread.sleep() Method Overview

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.

Two overloaded versions of sleep are provided:

  1. static void sleep(long millis) - Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.
  2. static void sleep(long millis, int nanos) - Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds plus the specified number of nanoseconds, subject to the precision and accuracy of system timers and schedulers.

Thread.sleep() Method Example

In this example, we have created and started two threads thread1 and thread2. note that we have used both overloaded versions of sleep() methods in this example.

Thread.sleep(1000);
Thread.sleep(1000, 500);
/**
 * thread sleep method examples
 * @author Ramesh fadatare
 *
 */
public class ThreadSleepExample {
	public static void main(final String[] args) {
		System.out.println("Thread main started");
		final Thread thread1 = new Thread(new WorkerThread());
		thread1.setName("WorkerThread 1");
		final Thread thread2 = new Thread(new WorkerThread());
		thread1.setName("WorkerThread 2");
		thread1.start();
		thread2.start();
		System.out.println("Thread main ended");
	}
}

class WorkerThread implements Runnable {

	@Override
	public void run() {
		for (int i = 0; i < 5; i++) {
			try {
				Thread.sleep(1000);
				Thread.sleep(1000, 500);
				System.out.println("[" + Thread.currentThread().getName() + "] Message " + i);
			} catch (final InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

Output:

Thread main started
Thread main ended
[WorkerThread 2] Message 0
[Thread-1] Message 0
[WorkerThread 2] Message 1
[Thread-1] Message 1
[WorkerThread 2] Message 2
[Thread-1] Message 2
[WorkerThread 2] Message 3
[Thread-1] Message 3
[WorkerThread 2] Message 4
[Thread-1] Message 4

Note that sleep() method throws InterruptedException exception, when another thread interrupts the current thread while sleep is active.