ADVERTISEMENT
ADVERTISEMENT

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 »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.