Sleeping thread


Sleeping thread

If we want the currently executing thread to sleep for a certain amount of time (e.g.:milliseconds), we can use java.lang.Thread.sleep(long millis) method.

Syntax:

Public static void sleep(long millis) throws InterruptedException millis is the amount of time to sleep in milliseconds.

The java.lang.Thread.sleep(long millis) system makes the presently running thread sleep for the defined number of milliseconds, directed to the precision and efficiency of system timers and schedulers.

The value of argument for milliseconds can never be negative, and it launches IllegalArgumentException.

Some Parameters of the sleep thread

  • millis − It is the duration of time to sleep in milliseconds.
  • Return Value - This approach does not return a value.
  • Exception

InterruptedException

When any of the threads disrupted the current thread. The disrupted status of the current thread is released when this exception is launched.

The thread.sleep() technique can be applied to pause the current thread running for a defined time in milliseconds.

Some points to remember on Java Thread Sleep

  • ⦁ This interrupts the current thread execution.
  • ⦁ The same time thread sleeps before waking up and begins execution depends on system timers and schedulers. To a calm system, the exact time for sleep is near the defined sleep time, but it will be a slight bit more for an occupied system.
  • ⦁ The java Thread sleep doesn’t drop any monitors or locks the current thread has collected.
  • ⦁ If any different threads interfere with the current thread in sleep, in such a case, an InterruptedException is launched.

Example:

Com.knowledge2life public class Main { public static void main(String[] args) throws InterruptedException { long start = System.currentTimeMillis(); Thread.sleep(2000); System.out.println("Sleep time in ms = "+(System.currentTimeMillis()-start)); } }

OUTPUT:

Sleep time in ms =2000