Java Thread sleep() methodThe sleep() method of thread class is used to sleep a thread for the specified amount of time. SyntaxParameterReturnThrowsIllegalArgumentException: 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 1Test it NowOutput: 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 negativeTest it NowOutput: 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) Next TopicMultithreading in Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India