Last Updated:

An example of using the sleep() method. Threads in Java

The class method is used to pause the execution of the current thread for a time specified in milliseconds. The argument value for milliseconds cannot be negative, otherwise it will be thrown.sleep()java.lang.ThreadIllegalArgumentException

There is another way to suspend the execution of the program: the . It is used to pause the execution of the current thread for the exact time in milliseconds and nanoseconds. The value of nanoseconds is valid between 0 and 999999.sleep(long millis, int nanos)

Here is a simple program that uses a method to pause the execution of the main thread for 2 seconds:Thread.sleep()

If you run the above program, you will notice that it stopped the thread from running for a little longer than 2000 milliseconds. The fact is that it all depends on the operating system and the specific implementation of the thread scheduler.

Important points in using the method sleep()

  • This method always suspends the execution of the current thread.
  • The actual time from stopping the stream to waking up depends on the system timers and schedulers. For a not-so-busy system, the actual time to sleep will be very close to the specified sleep time. For a busy system, this figure will be slightly higher.
  • Any other thread can interrupt a suspended thread. In this case, its execution is interrupted and an exception is thrown.