Java Thread sleep Example
In this article we are going to get an in depth understanding of:
- What is a thread in java?
- What is the use of
sleep()
in java thread based execution? - Important points to remember while using
Thread.sleep()
. - How
Thread.sleep()
works.
1. What is a thread in Java
Lets start with what the thread exactly is and how it is supported in Java.
Thread is a flow of execution in a program which shares the resources which is being use by the program itself and don’t have separate execution context as process.
Java has a rich set of Classes and Methods which enables us to utilize Java’s multi-threading environment very efficiently. We can just focus on our business logic without worrying about actual memory, resource, priority, and scheduling kind of implementation while writing multi-threaded applications.
In Java, all the threads are by default non-demon thread which means they will get terminated by returning by the call of run method or by throwing an exception.
Each thread have some priority number associated with it and gets inherited by the thread going to be stared from it. Thread having higher priority gets executed before the thread having less priority.
1.1 Main thread in Java
In Java, all programs start with a non-demon thread which starts its execution without we explicitly being started which is the main thread.
1.2 Creating Thread in Java
There are two possible ways to create a new thread in java-
- By declaring a class and extending it from
java.lang.Thread
class as given below-
New Thread by extending Teread class
class MyThread extends Thread { public void run() { sendEmail(); } public void sendEmail(){ // Email sending logic } }
We can start the above thread as given below-
Starting the thread extendin Thread class
MyThread p = new MyThread(); p.start();
The other way of creating a new thread in java is by declaring a class implementing Runnable
interface and providing its run() method implementation.
New Thread by implementing Runnable interface
class MyThread implements Runnable { public void run() { sendEmail(); } public void sendEmail(){ // Sending Email Logic } }
We can start the above thread as given below-
Starting thread implementing Runnable interface
MyThread p = new MyThread(143); new Thread(p).start();
2. What is the use of sleep() in Java thread based execution?
Thread class sleep()
causes currently running thread to go into sleep for a specified time duration. There are two flavors of sleep()
are there in java threads-
public static void sleep(long millis) throws InterruptedException public static void sleep(long millis,int nanos) throws InterruptedException
In the first flavor, we can pass a number of milliseconds the thread execution need to be paused and in the other one, we can pass the number of milliseconds plus the number of nanoseconds as sleeping period.
In both methods, if we pass any negative value It will throw IllegalArgumentException
and if the thread gets interrupted by any other thread while it is sleeping It will throw InterruptedException
3. Important Points to remember
Thread.sleep()
always pauses the current thread execution-
Thread.sleep()
doesn’t guarantees that thread wakes up exactly after the time specified in sleep(). It up to the schedule it can be more time if the system is busy in performing other task or any other thread is running. - when Thread.sleep() gets called current thread immediately releases all resources associated with the current thread like monitors and locks.
- in case of any interruption by another thread it throws
InterruptedException
.
4. Working of Thread.sleep()
As soon as Thread.sleep()
gets called, current thread contacts to put it into wait state and immediately releases any resources associated with it and goes into the sleep state. Again when the sleep period is over scheduler put the current thread into runnable
state and based on scheduling algorithm it resumes its execution.
5. Example of Thread.sleep()
It is very easy to use Thread.sleep()
. just call it in any thread whose execution needed to be paused for some time.
Using thread.sleep()
public class ThreadSleepDemo { public static void main(String[] args) { long start = System.currentTimeMillis(); System.out.println("Main thread starting at:" + start); // sleeping for 2 second try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } long end = System.currentTimeMillis(); System.out.println("Main thread ending at:" + end); System.out.println("actual pause time: " + (end - start)); } }
Result
Main thread starting at:1562783281533 Main thread ending at:1562783283534 actual pause time: 2001
As we can see in above example the actual pause time defers than expected as mentioned in above section.
That leads to end to the article. Hope It was helpful for you.
6. Additional Knowledge
7. Download the Source Code
This was an example of Java Thread sleep
You can download the full source code of this example here: Java Thread sleep Example