πŸŽ‰ Special Offer !    Code: GET300OFF    Flat β‚Ή300 OFF on every Java Course
Grab Deal πŸš€

sleep() Method in Java  


Introduction
  • The sleep() method in Java is used to pause the execution of the current thread for a specified amount of time (in milliseconds or nanoseconds).
  • During the sleep period, the thread goes into a Timed Waiting state but does not lose ownership of any monitors (locks).
  • Real-World Examples where sleep() is used:
    • Digital Clock: Updating the time display every second using Thread.sleep(1000).
    • Animation: Adding delay between frames for smooth animation effects.
    • Polling: Waiting before checking a resource again (e.g., server status, database updates).
    • Simulation: Creating realistic delays in simulations like traffic lights or game loops.
    • Task Scheduling: Running periodic tasks at fixed intervals in applications.
  • To sleep or pause thread execution, Java has provided two overloaded methods in the Thread class:
    1. public static native void sleep(long millis) throws InterruptedException
      • This is a native method, meaning its implementation is provided in another language (like C/C++) inside the JVM.
      • Pauses the currently executing thread for the specified time in milliseconds.
      • Example: Thread.sleep(1000); β†’ pauses execution for 1 second.
      • Throws InterruptedException if another thread interrupts the current thread while sleeping.
    2. public static void sleep(long millis, int nanos) throws InterruptedException
      • This is a normal Java method (non-native).
      • It internally calls the native sleep(long millis) method after adjusting the value of millis based on the nanos parameter.
      • Pauses the current thread for the specified time in milliseconds + nanoseconds.
      • millis = number of milliseconds, nanos = additional time in nanoseconds (0–999999).
      • More precise than the single-parameter version (used for high-precision timing).
      • Also throws InterruptedException if interrupted while sleeping.
  • Program:
    public class SleepExample
    {
        public static void main(String[] args)
        {
            for (int i = 1; i <= 5; i++)
            {
                System.out.println(i);
                try
                {
                    Thread.sleep(1000); // Pause for 1 second
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }
  • Important Key Points about sleep() method:
    • sleep() is a static method of the Thread class.
    • It is used to pause the execution of the currently running thread for a specified time.
    • During sleep, the thread enters the Timed Waiting state.
    • It does not release the lock (monitor) if the thread is holding one.
    • It throws InterruptedException, so it must be handled using try-catch or declared with throws.
    • It affects only the current thread, not other threads.
    • The actual time the thread sleeps may be longer than specified due to OS scheduling and system timers.
    • Negative values are not allowed in sleep(); passing them will throw IllegalArgumentException.
    • The sleep() method is declared as native, meaning its implementation is provided in another language (like C/C++) within the JVM.