Sunday, November 27, 2011

Pause Thread Using Sleep Method Example


  1. /*
  2.   Pause Thread Using Sleep Method Example
  3.   This Java example shows how to pause currently running thread using
  4.   sleep method of Java Thread class.
  5. */
  6.  
  7. public class PauseThreadUsingSleep {
  8.  
  9. public static void main(String[] args) {
  10.  
  11. /*
  12. * To pause execution of a thread, use
  13. * void sleep(int milliseconds) method of Thread class.
  14. *
  15. * This is a static method and causes the suspension of the thread
  16. * for specified period of time.
  17. *
  18. * Please note that, this method may throw InterruptedException.
  19. */
  20.  
  21. System.out.println("Print number after pausing for 1000 milliseconds");
  22. try{
  23.  
  24. for(int i=0; i< 5; i++){
  25.  
  26. System.out.println(i);
  27.  
  28. /*
  29. * This thread will pause for 1000 milliseconds after
  30. * printing each number.
  31. */
  32. Thread.sleep(1000);
  33. }
  34. }
  35. catch(InterruptedException ie){
  36. System.out.println("Thread interrupted !" + ie);
  37. }
  38.  
  39. }
  40. }
  41.  
  42. /*
  43. Output of this example would be
  44.  
  45. Print number after pausing for 1000 milliseconds
  46. 0
  47. 1
  48. 2
  49. 3
  50. 4
  51. */

1 comment:

How to find the most appropriate Keywords?

  🔍 Step 1: Understand Your Business and Audience Define your products, services, or content . Identify your target audien...