Sunday 29 January 2012

Thread.sleep() method in Java with Examples

Thread.sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system.

Thread.sleep() sends the current thread into the "
Not Runnable" state for a specified amount of time.Also,if another thread calls t.interrupt(), it will wake up the sleeping thread.

sleep is a static method, which means that it always affects the current thread (the one that is executing the sleep method).It is a common mistake to call t.sleep() where t is a different thread; even then, it is the current thread that will sleep, not the t thread.

One thread can't make sleep another thread t using t.sleep method.Only the current thread which is executing the statement 't.sleep' will go for sleep.

Sleep doesn’t cause the thread to lose ownership of the acquired monitors.The thread keeps the monitors it has acquired i.e. if the thread is currently in a synchronized block or method no other thread can enter this block or method.

Thread.sleep method is available in two different formats as given below

public static void sleep(long millis) throws InterruptedException 
    Parameters:
    millis - the length of time to sleep in milliseconds. 
 
public static void sleep(long millis,int nanos) throws InterruptedException
    Parameters:
     millis - the length of time to sleep in milliseconds.
     nanos - 0-999999 additional nanoseconds to sleep. 
 
Let us see the difference between these two methods.
 
public static void sleep(long millis) throws InterruptedException  
 
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.The method throws InterruptedException ,if another thread has interrupted current thread.So always keep the Thread.sleep statement within a try-catch block.
 
public static void sleep(long millis,int nanos) throws InterruptedException

This method is exactly same as the above one.Only one difference is that you can specify the timeout value more accurately,i.e. in the order of nano seconds.

Let us see one example ,here we are using Thread.sleep(1000) method to sleep the main thread for a 1000ms.

import java.util.Date;

public class Main {
    public static void main(String args[]) {

        System.out.println("Hello-----" + new Date());
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Welcome-----" + new Date());

    }
}

The output is given below

Hello-----Sun Jan 29 22:03:26 IST 2012
Welcome-----Sun Jan 29 22:03:27 IST 2012

You can see that ,there is delay of 1sec in between printing 'Hello' and 'Welcome'.The reason is that Thread.sleep(1000) caused the current thread,main thread to sleep for 1sec after printing 'Hello'.


Let us see one more example. If one thread tries to sleep another thread,what will happen,will it work ?

class MyThread1 extends Thread {

    public void run() {
        while (true) {
            System.out.println("From the MyThread1");
        }
    }
}

class MyThread2 extends Thread {
    MyThread1 thread1;

    MyThread2(MyThread1 thread1) {
        this.thread1 = thread1;
    }

    public void run() {
        while (true) {
            System.out.println("From the MyThread2");
            try {
                thread1.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class Main {

    public static void main(String args[]) {

        MyThread1 thread1 = new MyThread1();
        MyThread2 thread2 = new MyThread2(thread1);
        thread1.start();
        thread2.start();

    }
}

The output is given below

From the MyThread1
From the MyThread1
From the MyThread1
From the MyThread1
From the MyThread1
From the MyThread2 (After each 1000 ms)
From the MyThread1
From the MyThread1
From the MyThread1
From the MyThread1
From the MyThread1
From the MyThread2 (After each 1000 ms)

Here thread2 is trying to sleep thread1 for 1000 ms in each iteration of the loop.As we said early ,one thread can't sleep another thread t using the function t.sleep,only the current thread which is executing t.sleep will go for sleep.

In our example the statement thread1.sleep(1000); is executing by the thread thread2 in each iteration of the loop .Hence thread2 will sleep for 1000 ms in each iteration of the loop as shown in the above output. 

2 comments:

  1. Great explanation of this popular interview question. I have also shared my view as sDifferences between sleep and wait in Java, let me know how do you find it.

    ReplyDelete