Java Thread.sleep() method Example
Thread.sleep
method of current thread suspends the execution of a program for a specific time. This method is generally used for giving the execution time to another Thread.
There are two version of sleep method provided.
- Thread.sleep(long millis)– specifies the sleep time to the millisecond.
- Thread.sleep(long millis, int nanos)– specifies the sleep time to the nanosecond.
Note: sleep() throws
InterruptedException
exception when another thread interrupts the current thread while sleep is active andIllegalArgumentException
– if the value of millis is negative.
SleepMethodExp.java
package org.websparrow.thread.methods;
public class SleepMethodExp extends Thread {
@Override
public void run() {
try {
for (int i = 1; i <= 10; i++) {
int var = 2 * i;
// Pause for 1 seconds
Thread.sleep(1000);
System.out.println(var);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SleepMethodExp sleepMethodExp = new SleepMethodExp();
sleepMethodExp.run();
}
}
SleepMethodExp1.java
package org.websparrow.thread.methods;
public class SleepMethodExp1 extends Thread {
@Override
public void run() {
try {
for (int i = 1; i <= 10; i++) {
int var = 2 * i;
// Pause for 1000 millis seconds and 500 nano seconds
Thread.sleep(1000, 500);
System.out.println(var);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SleepMethodExp1 sleepMethodExp1 = new SleepMethodExp1();
sleepMethodExp1.run();
}
}