java tutorial - Thread.sleep in Java - java programming - learn java - java basics - java for beginners



Thread sleep java

Learn Java - Java tutorial - Thread sleep java - Java examples - Java programs

  • Thread.sleep() is used to stop an execution of current thread for a particular time given in milliseconds.
  • An argument value for milliseconds cannot be negative, or else it throws IllegalArgumentException.

Syntax

  • The Thread class provides two methods for sleeping a thread:
    • public static void sleep(long miliseconds)throws InterruptedException
    • public static void sleep(long miliseconds, int nanos)throws InterruptedException

Java Thread Sleep

  • It always pause the current thread execution.
  • The actual time thread sleeps before waking up and start execution depends on system timers and schedulers. For quiet system, actual time for sleep is just close to the specified sleep time however for a busy system it will be little bit more.
  • Thread sleep doesn’t lose any monitors or else locks current thread has acquired.
  • Any other thread can interrupt the current thread in sleep; in that case InterruptedException is thrown.

How Thread Sleep Works

  • Thread.sleep() interacts with thread scheduler to set the current thread in waiting state for specified period of time.
  • Once the wait time is over, thread state is changed to runnable state and wait for the CPU for further execution.
  • So the actual time that current thread sleep depends on the thread scheduler which is part of operating system.

Sample Code

public class SleepMethod extends Thread{  
 public void run()
 {  
  for(int i=0;i<6;i++)
  {  
    try
    {
        Thread.sleep(400);
        
    }
    catch(InterruptedException e)
    {
        System.out.println(e);
        
    }  
        System.out.println(i);  
  }  
 }  
 public static void main(String args[]){  
  SleepMethod time1=new SleepMethod(); 
  time1.start();   
 }  
}  
click below button to copy the code. By - java tutorial - team

Output

0
1
2
3
4
5

Related Searches to Thread.sleep in Java