Home »
Java Programs »
Java Most Popular & Searched Programs
Java code for pause the execution
Pausing thread execution in Java: Here, we are going to learn how to pause the execution of a thread?
Submitted by IncludeHelp, on July 14, 2019
While working on the threads, sometimes we need to pause the execution of any thread – in that case, we need the concept of pausing the thread execution.
To pause the execution of a thread, we use "sleep()" method of Thread class.
Syntax:
Thread.currentThread().sleep(milliseconds);
Example:
Thread.currentThread().sleep(1000); //will pause the thread for 1 second
Thread.currentThread().sleep(10000); //will pause the thread for 10 seconds
Java code to pause the execution of a thread
//Java code to pause the execution of a thread
class ThreadPause {
// method to pause the string
// here we will pass the time in seconds
public void wait(int sec) {
try {
Thread.currentThread().sleep(sec * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// main code
public class Main {
public static void main(String args[]) {
ThreadPause TP = new ThreadPause();
System.out.println("Waiting 1 second...");
TP.wait(1);
System.out.println("Done");
System.out.println("Waiting 10 seconds...");
TP.wait(10);
System.out.println("Done");
}
}
Output
Waiting 1 second...
Done
Waiting 10 seconds...
Done
Java Most Popular & Searched Programs »