«Back to Home

Core Java

Topics

sleep() Method In Java

sleep() method
 
The Thread class sleep() method is used to sleep a thread for the particular duration of time.
 
In other words, java.lang.Thread.sleep(long millis) method causes the presently executing thread to sleep for the specific number of milliseconds, subject to the precision and accurateness of the system timers and schedulers.
 
The Thread class provides two methods for sleeping a thread, which are,
 
Syntax

public static void sleep(long miliseconds)throws InterruptedException
 
public static void sleep(long miliseconds, int nanos)throws InterruptedException
 
Let’s see an example of sleep method, which is given below.
 
Code
  1. public class SleepMethod extends Thread {  
  2.     public void run() {  
  3.         for (int i = 0; i < 10; i++) {  
  4.             try {  
  5.                 Thread.sleep(1000);  
  6.             } catch (InterruptedException e) {  
  7.                 System.out.println(e);  
  8.             }  
  9.             System.out.println(i);  
  10.         }  
  11.     }  
  12.     public static void main(String args[]) {  
  13.         SleepMethod t1 = new SleepMethod();  
  14.         SleepMethod t2 = new SleepMethod();  
  15.         t1.start();  
  16.         t2.start();  
  17.     }  
  18. }  
7

Output

8

In the example, mentioned above, we know that at a time, only one thread is executed. If one thread sleeps for the specified time then the thread scheduler picks up another thread and so on.
 
Summary

Thus, we learnt that the Thread class sleep() method is used to sleep a thread for the particular amount of time and also learnt, how to use join() method in Java.