Java Thread Sleep

In a multithreading environment, multiple threads can run concurrently. But there may be a situation when we want to pause the execution of a thread for a specific amount of time. To pause the execution of a thread for a specific time we can use the sleep() method in java. In this post, we will see how to use in java thread sleep() method and how it works?

Here is the table content of the article will we will cover this topic.
1. Real-life example in java thread sleep() method
2. What is thread sleep() in java?
3. public static native void sleep(long millions)
i) How sleep method is working?
ii) Use of sleep method in multiple threads
4. public static void sleep(long millis, int nanos)
i) How sleep method is working?
5. Important Points to about java thread sleep

Let’s say we have three threads, thread1, thread2, and thread3. Now suppose all threads are in the RUNNABLE state it means they all are executing by CPU, but we want to stop the execution of thread1 only for some time period. Then we used the sleep() method. We can call it by class name because it is a static method.

className.sleep();

When JVM executes the above line, it moves the control flow from thread1. But there is no guarantee which thread will be the next for execution. It totally depends on the thread scheduler.

Real-life example in java thread sleep() method

Let’s say we are downloading two files from the internet. File1 (Which is thread1) is in downloading state but file2(Which is thread2) is waiting for the server. So now I want to stop the downloading of file1 for some time period which means we can use the sleep() method.  

After calling Thread.sleep(). The CPU can execute any thread it totally depends upon the thread scheduler.

What is thread sleep() in java?

The sleep() method is used to pause the execution of a thread for a specific time. The sleep() method is a static method and it exists in the Thread class. We can use it to sleep a thread for a millisecond or millisecond and nanoseconds. It is an overloaded method and there are two flavors of the sleep() method. We will discuss them one by one.

public static native void sleep(long millis) throws InterruptedException;

public static void sleep(long millis, int nanos) throws InterruptedException

public static native void sleep(long millis)

This method is used to sleep the thread for a specific time and it tasks milliseconds as an argument.  The argument value for milliseconds can’t be negative, if we provide a negative value it will throw an IllegalArgumentException. If any other thread interrupts the current sleeping thread. It throws an exception in this case.

java thread sleep

public: It’s just an access modifier that tells the method is public and we can access it outside the class.

static: As it is a static method so we can access it through the class name.

native: The sleep method is a native method which means it is written in another language like C, or C++.

void: It doesn’t return anything

sleep: The name of the method that we can use to call.

millis: It’s an argument of a long type in which we can specify the amount of time. The amount of time always considers in milliseconds.

throws: The throws keyword is used to throw the InterruptedException exception if any other thread interrupts while sleeping the current thread.

When JVM encounters the sleep() method in the program it pauses the execution of that thread in which it is written. When a thread is sleeping thread is not scheduled by the operating system scheduler to receive the CPU time. Let’s understand it with an example:

public class SleepExample
{
    public static void main(String arg[]) throws InterruptedException
    {
    	for(int i = 1; i <= 5; i++)
    	{
    		System.out.println(i);
    		Thread.sleep(1000);
    	}
    }
}

Output: 1
2
3
4
5

In the above you can see we are using the sleep() method to sleep the main thread. If you are not familiar with the main thread, please read the main thread first.

Here we are printing the count 1 to 5 and each number is printing after 1 second because we are using sleep(1000)

How does sleep method work?

java thread sleep

Step1: In the above example, JVM starts the execution from the main method and also creates the main thread to execute the program.

Step2: Start execution of for loop and printing the value 1.

Step3: Now JVM encountered the Thread.sleep(1000), it pauses the execution of the current thread(In the above example we have only one thread which is the main thread) for 1 second.

Step4: Again, start the execution of for loop and so on.

Use of sleep method in multiple threads

public class ExampleOfSleepMethod extends Thread
{  
   public void run()
   {  
     for(int i = 1; i <= 5; i++)
     {  
        System.out.println(Thread.currentThread().getName() + " is running and i = "+i);  
        try 
	{
	     Thread.sleep(1000); // Sleep the current thread for 1 second
	} catch (InterruptedException e) 
	{
	    e.printStackTrace();
	}
     }  
  }  
  public static void main(String args[])
  {  
	 ExampleOfSleepMethod  thread1 = new ExampleOfSleepMethod ();  
	 thread1.setName("Thread1");
	 ExampleOfSleepMethod  thread2 = new ExampleOfSleepMethod ();
	 thread2.setName("Thread2");
		 
	 thread1.start();  
				
	 thread2.start();  
   }  
}

Output: Thread1 is running and value of i = 1

Thread2 is running and value of i = 1

Thread1 is running and value of i = 2

Thread2 is running and value of i = 2

Thread2 is running and value of i = 3

Thread1 is running and value of i = 3

Thread2 is running and value of i = 4

Thread1 is running and value of i = 4

Thread2 is running and value of i = 5

Thread1 is running and value of i = 5

Suppose we have two threads thread1 and thread2. Both threads are printing the counting of numbers from 1 to 10. Thread1 is printing odd numbers and thread2 is even numbers. So we will try to print the count from 1 to 10 in a sequence and each number will print after one second.

class ThreadOne extends Thread
{
	public void run()
	{
		for(int i = 1; i <= 10; i+=2)
         	{
    		   System.out.println(i);
    		   try 
    		   {
			Thread.sleep(1000);
		   } 
    		   catch (InterruptedException e) 
    		   {
				e.printStackTrace();
       		   }
    	     }
	}
}
class ThreadTwo extends Thread
{
	public void run()
	{
		for(int i = 2; i <= 10; i+= 2)
    	       {
		   System.out.println(i);
    		   try 
    		   {
				Thread.sleep(1000);
	     	   } 
    		   catch (InterruptedException e) 
    		   {
				e.printStackTrace();
		   }
    	       }
	}
}
public class SleepExample
{
    public static void main(String arg[]) throws InterruptedException
    {
    	ThreadOne thread1 = new ThreadOne();
    	ThreadTwo thread2 = new ThreadTwo();
    	
    	thread1.start();
    	thread2.start();
    }
}

In the above example, we are creating two threads and using Thread.sleep(1000). So, when JVM encounters the sleep() method in the running thread it is pausing the execution of the thread and controls the transfer to another thread.

NOTE: The output of the program can be varied on the different systems because we can’t predict when a thread will run exactly by the thread scheduler.

Step1: JVM starts the execution from the main method and creates two threads thread1 and thread2.

Step2: In the next two lines JVM starts the execution of the thread by calling the start() method. Both threads have gone running.

thread1.start();
thread2.start();

Step3: Thread1 is printing the number 1 and goes to sleep for 1 second. Meantime thread 2 has started the execution and printing of the number 2. The thread2 also goes to sleep for one second. Now control transfer to thread1 and so on.

Output: 1

2

3

4

5

6

7

8

9

10

In the above example, we created two threads thread1 and thread2. Both threads are used to print the counting. We called Thread.sleep() method for 1000 milliseconds in run() method. So, it sleeps the current running threads for one second and prints the output.

public static void sleep(long millis, int nanos)

This method is similar to the above method except for the argument list. It is also used to sleep the thread for a specific time and it tasks milliseconds and nanoseconds as an argument.  The argument value for milliseconds and nanoseconds can’t be negative, if we provide a negative value it will throw an IllegalArgumentException. If any other thread interrupts the current sleeping thread. It throws an exception in this case.

java thread sleep

public: It’s just an access modifier that tells the method is public and we can access it outside the class.

static: As it is a static method so we can access it through the class name.

native: The sleep method is a native method which means it is written in another language like C, or C++.

void: It doesn’t return anything

sleep: The name of the method that we can use to call.

millis: It’s an argument of a long type in which we can specify the amount of time. The amount of time always considers in milliseconds.

nanos: The allowed nano-second value is between 0 and 999999.

throws: The throws keyword is used to throw the InterruptedException exception if any other thread interrupts while sleeping the current thread.

public class SleepExample
{
    public static void main(String arg[]) throws InterruptedException
    {
    	for(int i = 1; i <= 5; i++)
    	{
    		System.out.println(i);
    		Thread.sleep(1000, 999999);
    	}
    }
}

Output: 1

2

3

4

5

Here we are printing the count 1 to 5 and each number is printing after 1 seconds and 999999 nanoseconds because we are using sleep(1000, 999999)

How does sleep method is working?

Step1: In the above example, JVM starts the execution from the main method and also creates the main thread to execute the program.

Step2: Start execution of for loop and printing the value 1.

Step3: Now JVM encountered the Thread.sleep(1000, 999999), it pauses the execution of the current thread(In the above example we have only one thread that is the main thread) for 1 second and 999999.

Step4: Again, start the execution of for loop and so on.

Important Points about java thread sleep

1. The sleep() method always pauses the current thread execution. When the  JVM finds the sleep() method in the code, it checks which thread is running and pause the execution of the thread.  After the pause of the current thread, the thread scheduler assigns the CPU to another thread if any thread exists. 

2. When we use the sleep() method to pause the execution of the thread. The thread scheduler schedule other thread for CPU time. So, there is no guarantee that the thread wakes up exactly after the time specified in the sleep() method. It totally depends on the thread scheduler.

3. When any thread is sleeping and any interruption by another thread then it throws InterruptedException.

4. Whenever we want to use the sleep() method we also need to handle the InterruptedException. If we will not handle it, the JVM will show a compilation error.

Leave a Comment