Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Pause Thread - Using Sleep() function in Java

  1. public class ThreadSleep{
  2. public static void main(String[] args) {
  3. /*
  4. * To pause execution of a thread, use
  5. * void sleep(int milliseconds) method of Thread class.
  6. *
  7. * This is a static method and causes the suspension of the thread
  8. * for specified period of time.
  9. *
  10. * Please note that, this method may throw InterruptedException.
  11. */
  12. System.out.println("Print number after pausing for 1000 milliseconds");
  13. try{
  14. for(int i=0; i< 5; i++){
  15. System.out.println(i);
  16. /*
  17. * This thread will pause for 1000 milliseconds after
  18. * printing each number.
  19. */
  20. Thread.sleep(1000);
  21. }
  22. }
  23. catch(InterruptedException ie){
  24. System.out.println("Thread interrupted !" + ie);
  25. }
  26. }
  27. }

Output:
Print number after pausing for 1000 milliseconds
0
1
2
3
4