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 –

class MultiThreadDemo extends Thread{

    public void run()
    {
        for(int i=0;i<5;i++)
        {
            System.out.println("Thread ID: "+currentThread().getId());
            try {
                sleep(1000);
            } catch (Exception ex) {
                Logger.getLogger(MultiThreadDemo.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

public class JavaApplication4 {

    public static void main(String[] args) {

        MultiThreadDemo t1 = new MultiThreadDemo();
        MultiThreadDemo t2 = new MultiThreadDemo();
        
        t1.start();
       
        t2.start();
        //MultiThreadDemo.sleep(1000);
    }
}

Output –

Thread ID: 10
Thread ID: 11
Thread ID: 10
Thread ID: 11
Thread ID: 10
Thread ID: 11
Thread ID: 11
Thread ID: 10
Thread ID: 11
Thread ID: 10

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 *