8/9/17

Thread Sleep Example

Sleep is method from Thread class. This can be called without object and will act on current running thread.

Calling sleep on current thread will throw InterruptedException that you need to handle in your code.

When a thread goes to sleep, it does not release it's resources then and there because after certain time it will awake and need those resources.

Let's see in example below


package com.techiekunal.examples;

class MyRunnable implements Runnable{

 @Override
 public void run() {
  System.out.println("Thread going to sleep :- " + Thread.currentThread().getName());
  try {
   Thread.sleep(10000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  System.out.println("Thread wakenup is :- " + Thread.currentThread().getName());
 }
}


public class SleepExample {

 public static void main(String[] args) {
  Thread t1 = new Thread(new MyRunnable(),"Bruno");
  Thread t2 = new Thread(new MyRunnable(),"Adam");
  
  t1.start();
  t2.start();
 }
}

Output will be :-


Thread going to sleep :- Bruno

Thread going to sleep :- Adam

Thread wakenup is :- Adam

Thread wakenup is :- Bruno