Pausing Execution with Sleep - Thread.sleep in Java

If You want to suspend executing of Thread for particular period of time then Thread.sleep is for You.Once You suspend particular thread, Thread scheduler pickups other threads which are waiting for execution.

Thread Class provides following two methods using which you can suspend thread for particular period of time.
  1. public static native void sleep(long millis) throws InterruptedException;
  2. public static void sleep(long millis, int nanos) throws InterruptedException

Each Thread has boolean property associated which it which represents Interrupted Status. It's false by default. But when any thread is interrupted by other Thread using Thread.interrupt(), If Thread is executing blocking methods like Thread.sleep,Thread.join or Object.wait then it unblocks and throw InterruptedException otherwise interrupt() sets Interrupted status will be updated to true.

You can check that Thread is interrupted or not using Thread.isInterrupted()

Java Program for Thread Sleeping :
package com.anuj.threading;

/**
 * Thread Sleep Example
 * @author Anuj
 *
 */
class ThreadSleepExample extends Thread{

 @Override
 public void run() {
  for(int i=1;i<=5;i++){
   System.out.println(Thread.currentThread().getName() + " - "+i);
   
   try {
    Thread.sleep(500);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }
 
 /**
  * @param args
  */
 public static void main(String[] args) {
  ThreadSleepExample t1 = new ThreadSleepExample();
  ThreadSleepExample t2 = new ThreadSleepExample();

  t1.start();
  t2.start();
 }

}

Output :
Thread-0 - 1
Thread-1 - 1
Thread-1 - 2
Thread-0 - 2
Thread-0 - 3
Thread-1 - 3
Thread-1 - 4
Thread-0 - 4
Thread-0 - 5
Thread-1 - 5

No comments:

Post a Comment