Java Tutorial/Thread/Sleep Pause

Материал из Java эксперт
Перейти к: навигация, поиск

Add a delay

   <source lang="java">

public class Main {

 public static void main(String[] args) {
   for (int i = 0; i < 10; i++) {
     System.out.println("i = " + i);
     try {
       Thread.sleep(1000);
     } catch (InterruptedException ie) {
       ie.printStackTrace();
     }
   }
 }

}</source>





Pause the execution

   <source lang="java">

class Wait {

 public static void oneSec() {
   try {
     Thread.currentThread().sleep(1000);
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
 }
 public static void manySec(long s) {
   try {
     Thread.currentThread().sleep(s * 1000);
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
 }

} public class Main{

 public static void main(String args[]) {
   Wait.oneSec();
   Wait.manySec(5);
 }

}</source>





Pause the execution of a thread using sleep()

   <source lang="java">

class Wait {

 public static void bySeconds(long s) {
   try {
     Thread.currentThread().sleep(s * 1000);
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
 }

} public class Main {

 public static void main(String args[]) {
   System.out.println("Wait");
   Wait.bySeconds(5);
   System.out.println("Done");
 }

}</source>





Pausing the Current Thread: a thread can temporarily stop execution.

   <source lang="java">

public class Main {

 public static void main(String[] argv) throws Exception {
   long numMillisecondsToSleep = 5000; 
   Thread.sleep(numMillisecondsToSleep);
 }

}</source>