What is Thread sleep?

The sleep() method is a static method of class Thread.We use it in your code
to "slow a thread down" by forcing it to go into a sleep mode before coming back to
runnable. When a thread sleeps, it drifts off somewhere and doesn't return to runnable until it wakes up.When a thread’s sleep() expires, and it wakes up, does not mean
it will return to running! Remember, when a thread wakes up, it simply goes back to
the runnable state.
So why would you want a thread to sleep?
imagine a thread that runs in a loop, downloading the latest stock prices and
analyzing them. Downloading prices one after another would be a waste of time, as
most would be quite similar—and even more important, it would be an incredible
waste of precious bandwidth. The simplest way to solve this is to cause a thread to
pause (sleep) for five minutes after each download.
We can do this by invoking the static Thread.sleep() method, giving it a time in
milliseconds as follows:
try {
Thread.sleep(5*60*1000); // Sleep for 5 minutes
} catch (InterruptedException ex) { }

Example:
class demo1 implements Runnable
{
public void run(){
for(int i=0;i<5;i++){
System.out.println("hi\t"+Thread.currentThread().getName());
try{Thread.sleep(1000);}catch(Exception e){}
}}
public static void main(String[] args){
demo1 d1=new demo1();
Thread t1=new Thread(d1,"abc");
Thread t2=new Thread(d1,"xyz");
t1.start();
t2.start();
}
}
The sleep() is a static method, so it is not possible that one thread can put another thread to sleep. You can put sleep() code anywhere, since all code is being run by some thread. When the executing code (meaning the currently running thread's code) hits a sleep() call, it puts the currently running thread to sleep.

No comments:

Post a Comment