Java TimeUnit.sleep(long timeout)

Syntax

TimeUnit.sleep(long timeout) has the following syntax.

public void sleep(long timeout)  throws InterruptedException

Example

In the following code shows how to use TimeUnit.sleep(long timeout) method.


//from  w  w  w . ja v a 2s .c o  m
import static java.util.concurrent.TimeUnit.SECONDS;

public class Main extends Thread {
  // This field is volatile because two different threads may access it
  volatile boolean keepRunning = true;

  public Main() {
    setDaemon(true);
  }

  public void run() {
    while (keepRunning) {
      long now = System.currentTimeMillis();
      System.out.printf("%tr%n", now);
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        return;
      }
    }
  }

  public void pleaseStop() {
    keepRunning = false;
  }

  public static void main(String[] args) {
    Main thread = new Main();
    thread.start();
    try {
      SECONDS.sleep(10);
    } catch (InterruptedException ignore) {
    }
    thread.pleaseStop();
  }
}




















Home »
  Java Tutorial »
    java.util.concurrent »




ArrayBlockingQueue
BlockingDeque
CountDownLatch
CyclicBarrier
TimeUnit