Java Thread sleep() Method Example



Java Thread Examples


This post describes the usage of the Java Thread sleep() method with an example.

Java Thread sleep() Method Overview

Thread.sleep() method 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.

Java 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.

Comments