Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – sleep() Method

Java Programming Language sleep Method in Multithreading

The sleep() method makes the thread sleep/stop working for a specific amount of time.

It is defined in Thread class, and its syntaxes are as follow:

                 public static void sleep(long milliseconds)

                 public static void sleep(long milliseconds, int nanoseconds)

The first method makes a thread sleep for some specific milliseconds only.

The second method makes a thread sleep for some specific milliseconds plus nanoseconds.

Example

class ChildThread extends Thread
{
    public void run()
    {
        for(int i=1;i<=5;i++)
        {
            System.out.println("Child Thread");
            try
            {
                Thread.sleep(500);
            }
            catch(InterruptedException e)
            {
                System.out.println("Exception caught");
            }
        }
    }
}

class SleepDemo
{
    public static void main(String args[])
    {
        ChildThread t = new ChildThread();
        t.start();
    }
}

Output

Child Thread
Child Thread
Child Thread
Child Thread
Child Thread

Here Child thread executes for loop five times with each iteration after every 500 milliseconds (1/2 second).

The sleep() method is surrounded by try-catch clause because it may throw an InterruptedException.

 

Leave a reply