Saturday, July 26, 2014

Sleeping a Thread

There are two overloaded methods of sleep in Thread class. The Thread object is sleep for specified amount of time. The sleep() method is a static method of class Thread. You use it in your code to "slow a thread down" by forcing it to go into a sleep mode before coming back to runnable. Notice that the sleep() method can throw a checked InterruptedException. Typically, you wrap calls to sleep() in a try/catch.

Example:

public class MyThread extends Thread{
    public void run(){
            try{
                for(int i=0;i<=5;i++){
            Thread.sleep(1000);
            System.out.println("Running here for.."+i);
                }
            }catch(InterruptedException ie){}
    }

    public static void main(String[] args){
        MyThread mt1 = new MyThread();
        MyThread mt2 = new MyThread();
        MyThread mt3 = new MyThread();
        mt1.start();
        mt2.start();
        mt3.start();
    }
}
Output:

Running here for..0
Running here for..0
Running here for..0
Running here for..1
Running here for..1
Running here for..1
Running here for..2
Running here for..2
Running here for..2
Running here for..3
Running here for..3
Running here for..3
Running here for..4
Running here for..4
Running here for..4
Running here for..5
Running here for..5
Running here for..5

Few Points to note here,

Just keep in mind that the behaviour in the preceding output is still not guaranteed.

When a thread encounters a sleep call, it must go to sleep for at least the specified number of milliseconds (unless it is interrupted before its wake-up time, in which case it immediately throws the InterruptedException).

Just because a thread’s sleep() expires, and it wakes up, does not mean it will return to running! When a thread wakes up, it simply goes back to the runnable state. So the time specifi ed in sleep () is the minimum duration in which the thread won’t run.

No comments :

Post a Comment