Thread sleep

In this chapter you will learn:

  1. How to make a thread sleep
  2. Pause the execution utilities
  3. Add a delay for each loop

Sleep a thread

The sleep() method causes the thread to suspend execution for the specified period of milliseconds. Its general form is shown here:

static void sleep(long milliseconds) throws InterruptedException

The number of milliseconds to suspend is specified in milliseconds. This method may throw an InterruptedException.

The sleep() method has a second form, shown next, which allows you to specify the period in terms of milliseconds and nanoseconds:

static void sleep(long milliseconds, int nanoseconds) throws InterruptedException

The following code makes the thread wait for one second.

Thread.sleep(1000); // Delay for 1 second

public class Main {
  public static void main(String[] argv) throws Exception {
    long numMillisecondsToSleep = 5000; 
    Thread.sleep(numMillisecondsToSleep);
  }/*ja  v  a 2 s . c o m*/
}

Pause the execution

The following class defines utility methods to stop the thread for a second or number of seconds.

We can use those methods when we want to stop the execution of current thread.

class Wait {//from ja v a 2 s .c om
  public static void oneSec() {
    try {
      Thread.currentThread().sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

  public static void manySec(long s) {
    try {
      Thread.currentThread().sleep(s * 1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}

public class Main{
  public static void main(String args[]) {
    Wait.oneSec();
    Wait.manySec(5);
  }
}

Add a delay

It illustrates the sleep method we can put the sleep method in a for loop and wait for one second for each loop.

public class Main {
  public static void main(String[] args) {
    for (int i = 0; i < 10; i++) {
      System.out.println("i = " + i);
/*from j ava2  s  . c  o m*/
      try {
        Thread.sleep(1000);

      } catch (InterruptedException ie) {
        ie.printStackTrace();
      }
    }
  }
}

Next chapter...

What you will learn in the next chapter:

  1. What are the two ways to create a thread
  2. Implementing Runnable interface
  3. Extending Thread class
Home » Java Tutorial » Thread
Thread introduction
Thread Name
Thread Main
Thread sleep
Thread Creation
Thread join and is alive
Thread priorities
Thread Synchronization
Interthread Communication
Thread Step
Thread suspend, resume, and stop
ThreadGroup
BlockingQueue
Semaphore
ReentrantLock
Executor
ScheduledThreadPoolExecutor