Core Java

Thread.sleep Java Example

In this article, we’ll discuss thread.sleep in Java along with some examples. We’ll start by explaining some details on threads, the importance of the sleep method, and then we will use examples of the sleep method.

You can also check this tutorial in the following video:

Java Threads Tutorial – video

1. What is a thread in Java

Threads are lightweight processes that allow concurrent execution of multiple activities. It allows us to perform synchronous processing and takes advantage of multiprocessor systems. Each thread is associated with an instance of class Thread.

Every thread has a priority. Threads will higher priority are executed in preference to threads with lower priority. Each thread may or may not also be marked as a daemon. When a JVM starts, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The JVM continues to execute threads until either of the following occurs:

  • The exit method of class Runtime has been called and security manager permits the exit operation to take place
  • All threads that are not daemon threads have died, either by returning from the call to run method or by throwing an exception that propagates beyond run method

An application that creates an instance of Thread must provide the code that will run in that thread. There are two ways to do this:

  • Provide a Runnable object: The Runnable interface defines a single method – run, meant to contain the code executed in the thread. The Runnable object is passed to the Thread constructor
  • Subclass Thread: The Thread class itself implements Runnable interface

Thread.start() will start the new thread for both the approaches mentioned above. Every thread has a name for identification purposes. A new name is generated if a name is not specified when the thread is created.

2. Why we use thread.sleep in Java

Thread.sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to other threads of an application or other applications that might be running on a computer system. The sleep method can also be used for pacing.

Two overloaded versions of sleep are provided: one that specifies the sleep time to millisecond, and the other that specifies sleep time to nanosecond (Details are available in Section 3 below). Note that these sleep times are not guaranteed to be precise, because they are limited by the facilities provided by the underlying OS.

3. Thread.sleep Java methods

As noted above, the sleep methods available in Thread are as follows:

  • public static void sleep (long millis) throws InterruptedException: Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.
  • public static void sleep (long millis, int nanos)throws InterruptedException: Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds plus the specified number of nanoseconds.

4. How thread.sleep() works

Let us look at an example to understand how thread.sleep() works.

import java.lang.InterruptedException;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;

public class SleepMessage{
    public static void main(String args[]) throws InterruptedException {
        // List of names to print
        String names[] = {"James","Peter","Harry","Jenny"};
        LocalTime time1, time2;
        
        // example for Thread.sleep(long millis)
        for(String strName: names){
            time1 = LocalTime.now();
            Thread.sleep(2000);
            time2 = LocalTime.now();
            System.out.println("Contacted " + strName + " in " + time1.until(time2, ChronoUnit.MILLIS) + " milli seconds.");
        }
        
        // example for Thread.sleep(long millis, int nanos)
        System.out.println("Let us now repeat with nano second delays");
        for(String strName: names){
            time1 = LocalTime.now();
            Thread.sleep(1000,800000);
            time2 = LocalTime.now();
            System.out.println("Contacted " + strName + " in " + time1.until(time2, ChronoUnit.NANOS) + " nano seconds.");
        }
        
    }
}

In the above example, we are printing the names with a sleep of 2 seconds (as indicated in line 14). We then repeat the same behavior with an additional sleep of 800000 nanoseconds after 1 second. The output would be as below:

Contacted James in 2002 milli seconds.
Contacted Peter in 2001 milli seconds.
Contacted Harry in 2001 milli seconds.
Contacted Jenny in 2000 milli seconds.
Let us now repeat with nano second delays
Contacted James in 1002000000 nano seconds.
Contacted Peter in 1002000000 nano seconds.
Contacted Harry in 1002000000 nano seconds.
Contacted Jenny in 1002000000 nano seconds.

Note that we get an IllegalArguementException if the time is specified in negative.

import java.lang.InterruptedException;

public class SleepErrorMessage{
    public static void main(String args[]) throws InterruptedException {
        // List of names to print
        String names[] = {"James","Peter","Harry","Jenny"};
        
        // example for Thread.sleep(long millis) with negative value
        for(String strName: names){
            Thread.sleep(-2000);
            System.out.println( strName );
        }
        
    }
}

The above code snippet would give the error as:

Exception in thread "main" java.lang.IllegalArgumentException: timeout value is negative
        at java.lang.Thread.sleep(Native Method)
        at java.lang.Thread.sleep(Thread.java:943)
        at SleepErrorMessage.main(SleepErrorMessage.java:10)

5. Download the source code

Download
You can download the full source code of this example here: Thread.sleep Java Example

Venkat-Raman Nagarajan

Venkat works for a major IT firm in India and has more than a decade of experience working and managing Java projects for a banking client.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button