Thread with sleep method
The sleep() method of Thread class is used to pause the execution of current thread for specified time.
This method takes the “long” value which is the actual time in milliseconds for thread to sleep.
There are 2 overloaded methods available for sleep()
1) public static void sleep(long millis) throws InterruptedException 2) public static void sleep(long millis,int nanos) throws InterruptedException
1) sleep(long millis) – This method Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.
If we pass negative value to the argument of sleep() method then it throws IllegalArgumentException.
2) sleep(long millis,int nanos) – This method Causes the currently executing thread to sleep(temporarily cease execution) for the specified number of milliseconds plus
the specified number of nanoseconds
If we pass negative value to the first argument of sleep() method then it throws IllegalArgumentException
For the second argument we need to pass value in the range of 0 to 999999 otherwise it throws IllegalArgumentException.
Both sleep() methods throws InterruptedException
– if any thread has interrupted the current thread
Example 1
Lets make main thread to sleep for 5 seconds
Create ThreadSleepExample1.java
- package com.kb.threads;
- public class ThreadSleepExample1 {
- public static void main(String[] args) throws InterruptedException {
- long startTime = System.currentTimeMillis();
- Thread.sleep(5000);
- System.out.println("Sleep time in milliseconds --> "+(System.currentTimeMillis()-startTime));
- }
- }
package com.kb.threads; public class ThreadSleepExample1 { public static void main(String[] args) throws InterruptedException { long startTime = System.currentTimeMillis(); Thread.sleep(5000); System.out.println("Sleep time in milliseconds --> "+(System.currentTimeMillis()-startTime)); } }
If we run the above program, we can notice that the thread sleeps for 5 seconds
But output will be slightly > 5000 milliseconds(5 seconds)
This is because thread went to sleep for 5000 milliseconds and then thread scheduler picks up this thread back to Running state and executes it.
Example2
Create ThreadSleepExample2.java
- class ThreadSleep extends Thread{
- public void run(){
- for(int i=1;i<4;i++){
- try{
- Thread.sleep(1000);
- }
- catch(InterruptedException ex){
- System.out.println(ex);
- }
- System.out.println(Thread.currentThread().getName()+" --> "+i);
- }
- }
- }
- public class ThreadSleepExample2 {
- public static void main(String[] args) {
- ThreadSleep t1 = new ThreadSleep();
- t1.setName("Thread 1");
- ThreadSleep t2 = new ThreadSleep();
- t2.setName("Thread 2");
- t1.start();
- t2.start();
- }
- }
class ThreadSleep extends Thread{ public void run(){ for(int i=1;i<4;i++){ try{ Thread.sleep(1000); } catch(InterruptedException ex){ System.out.println(ex); } System.out.println(Thread.currentThread().getName()+" --> "+i); } } } public class ThreadSleepExample2 { public static void main(String[] args) { ThreadSleep t1 = new ThreadSleep(); t1.setName("Thread 1"); ThreadSleep t2 = new ThreadSleep(); t2.setName("Thread 2"); t1.start(); t2.start(); } }
We can see that , first thread prints value and then goes for sleep for 1 second then second thread prints value and goes for sleep for 1 second and it executes in the same way for each iteration in loop.
How Thread’s sleep() method works internally ?
Whenever we call Thread.sleep() method , it will interact with the thread scheduler to put the current thread to wait state for a specified period of time.
Once the wait time is over, thread state changes from “Wait” to “Runnable” state.
It keeps waiting again for thread scheduler to pick it up and make it Run.
So the actual time it waits after sleep time to get the CPU allocation depends on the thread scheduler and the underlying Operating system.
Important points to remember about Thread’s sleep() method
It’s a static method defined in Thread class and hence we call it using class name.
The actual time thread takes to go for Running status after wait period is dependent on Thread scheduler and operating system.
When we call Thread.sleep() on currently running thread, it goes for sleep and thread scheduler picks up another thread for execution
Any other thread interrupting the current thread which is sleeping causes InterruptedException
Calling sleep() method on current thread does not result in loosing locks which it has acquired.