Java Clear Concepts: Java sleep method Example

Java Clear Concepts: Java sleep method Example

Java sleep method

One of the features of Java is its support for multithreading. A Java program can be divided into multiple threads and executing each thread with a different functionality. Sometimes, it may be required to temporarily stop the thread execution for a specified time. The easiest way is using sleep() method of Thread class.

Signature of Java sleep method

1. public static native void sleep(long milliseconds) throws InterruptedException
2. public static native void sleep(long milliseconds, int nanoseconds) throws InterruptedException

The parameter is time in milliseconds to pause the thread execution. The second overloaded sleep() method time in nanoseconds depends on the precision and accuracy of system timers and schedulers.

The sleep() method stops the execution of the right now running thread (called as current thread) for the specified time. It is declared static so that it can be called just by class name. "native" means, the sleep() method execution Java cannot do alone but depends on the underlying operating system. This method throws a checked exception "InterruptedException" and should be handled else program does not compile.

Let us use sleep() method in an example. The following example creates, starts and executes thread by extending Thread class. The execution should print 0 to 9 numbers with an interval of 1000 milliseconds (1 second) using sleep(1000).

Java sleep method

In the above code, d1 is an object of Demo class. But, we can call d1 as thread of Demo class as Demo extends Thread class. We can say, proudly we created a thread d1. But the thread d1 is inactive by default. To make it active, call start() on it. start() is a method of Thread class. When the thread is active, it calls implicitly run() method. run() is another method of Thread class.

The sleep(1000) makes every iteration to pause (stop) by 1000 milliseconds or to say, the thread is inactivated by 1000 milliseconds. An inactive thread is not eligible for microprocessor time. sleep() method is declared static so that it need not be called with object and also, in Thread.sleep(), the Thread represents the current thread. For this reason, sleep() is declared as static. sleep() method throws a checked exception "InterruptedException" and is handled in catch block.

More clear explanation of Java sleep method is available at Java Create Threads

Leave a Reply

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