Q:

Java code for pause the execution

belongs to collection: Java Most Popular & Searched Programs

0

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

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Program for Getting System UUID for Linux Mac... >>
<< Java code to run multiple threads in a program...