Sleep Method in Java Multithreading

The java.lang.Thread.sleep(long millis) method causes the currently executing thread to sleep for the specified number of milliseconds.

Declaration

The Thread class provides two methods for sleeping a thread:

  • public static void sleep(long miliseconds)throws InterruptedException
  • public static void sleep(long miliseconds, int nanos)throws InterruptedException
Parameters

millis − This is the length of time to sleep in milliseconds.

Return Value

This method does not return any value.

Exception

InterruptedException − if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.

Lets see a program example where we use the sleep method –

Output –

As you know well that at a time only one thread is executed. If you sleep a thread for the specified time,the thread shedular picks up another thread and so on.

Leave a Reply

Your email address will not be published. Required fields are marked *