Java Tutorial/Thread/Sleep Pause
Содержание
Add a delay
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();
}
}
}
}
Pause the execution
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);
}
}
Pause the execution of a thread using sleep()
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");
}
}
Pausing the Current Thread: a thread can temporarily stop execution.
public class Main {
public static void main(String[] argv) throws Exception {
long numMillisecondsToSleep = 5000;
Thread.sleep(numMillisecondsToSleep);
}
}