Credits

Tuesday, August 10, 2010

Java Thread's Sleep Method

You can use several methods with threads including start ( ), join ( ), wait ( ) and even sleep ( ). The sleep is used to allow the thread to pause in milliseconds ( 1 second = 1000 milliseconds). Thus, if you need 60 seconds or 1 minute, simply write,

sleep(60000);

But, sleep method works with try and catch blocks to accept InterruptedException during pause. Check the program below for our sample.

[+/-] show/hide



class HelloThread2{
public static void main(String[] args){
HelloThread1 myHello=new HelloThread1();
myHello.start();
}
}

class HelloThread1 extends Thread {
private static final int TIMES =5;
public void run()
{
for(int x=1;x<=TIMES;x++) { System.out.println("Hello"); if (TIMES==4) try{ sleep(60000); } catch (InterruptedException e) { } } } }

AddThis