Java - Thread Sleep by TimeUnit

Introduction

TimeUnit enum in java.util.concurrent package represents a measurement such as milliseconds, seconds, minutes, hours, days, etc.

TimeUnit enum has the sleep() method.

To sleep a thread for five seconds, use the sleep() method of TimeUnit instead to avoid the time duration conversion.

TimeUnit.SECONDS.sleep(5); // Same as Thread.sleep(5000);

Demo

import java.util.concurrent.TimeUnit;

public class Main {
  public static void main(String[] args) {
    try {//from w w  w .  ja v a  2 s.c  om
      System.out.println("I am going to sleep for 5 seconds.");
      TimeUnit.SECONDS.sleep(5); // The "main" thread will sleep
      System.out.println("I woke up.");
    } catch (InterruptedException e) {
      System.out.println("Someone interrupted me in my sleep.");
    }
    System.out.println("I am done.");
  }
}

Result

Related Topic