Home » Java Thread sleep() Method with Examples

Java Thread sleep() Method with Examples

by Online Tutorials Library

Java Thread sleep() method

The sleep() method of thread class is used to sleep a thread for the specified amount of time.

Syntax

Parameter

Return

Throws

IllegalArgumentException: If the value of millis is negative or the value of nanos is not in the range 0-999999.

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

Example 1

Test it Now

Output:

1  1  2  2  3  3  4  4  5  5  

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

Example 2: when sleep time is negative

Test it Now

Output:

Exception in thread "Thread-0" Exception in thread "Thread-1" java.lang.IllegalArgumentException: timeout value is negative  at java.lang.Thread.sleep(Native Method)  at SleepExp2.run(SleepExp2.java:9)  java.lang.IllegalArgumentException: timeout value is negative  at java.lang.Thread.sleep(Native Method)  at SleepExp2.run(SleepExp2.java:9)  

You may also like