In this section we are going to describe sleep() method with example in java thread.
sleep() method :
Suppose you want to stop your thread for a specific time period, you can use sleep() method. The Thread.sleep() method pauses the current thread for a specified time period.
sleep(long millis) : It puts the current executing
thread to sleep for a given number of milliseconds.
millis - It defines the length of time in milliseconds.
sleep(long millis, int nanos) : It puts the current
executing thread to sleep for a given number of milliseconds and nanoseconds.
millis - It defines the length of time in milliseconds.
nanos - It defines additional nanoseconds to sleep. It ranges
0-999999.
Example :
public class ThreadSleep implements Runnable {
Thread thread;
public void run() {
System.out.println(Thread.currentThread().getName() + " ");
try {
/*
* sleep for the specified number of milliseconds and nanoseconds
*/
System.out.println("Calling sleep() method...");
Thread.sleep(100, 100);
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) throws Exception {
Thread thread1 = new Thread(new ThreadSleep());
Thread thread2 = new Thread(new ThreadSleep());
thread1.start();
thread2.start();
thread1.join();
System.out.println(thread1.getName() + " commpleted");
thread2.join();
System.out.println(thread2.getName() + " commpleted");
}
}
Output :
Thread-0 Calling sleep() method... Thread-1 Calling sleep() method... Thread-0 commpleted Thread-1 commpleted