我希望第二次打印在2秒后发生.
System.out.println("First print.");
//I want the code that makes the next System.out.println in 2 seconds.
System.out.println("This one comes after 2 seconds from the println.");
Run Code Online (Sandbox Code Playgroud)
只需使用Thread#sleep:
System.out.println("First print.");
Thread.sleep(2000);//2000ms = 2s
System.out.println("This one comes after 2 seconds from the println.");
Run Code Online (Sandbox Code Playgroud)
注意,Thread.sleep可以抛出一个InterruptedException,所以你需要一个throws或一个子句try-catch,如:
System.out.println("First print.");
try{
Thread.sleep(2000);//2000ms = 2s
}catch(InterruptedException ex){
}
System.out.println("This one comes after 2 seconds from the println.");
Run Code Online (Sandbox Code Playgroud)
要么:
public void something() throws InterruptedException {
System.out.println("First print.");
Thread.sleep(2000);//2000ms = 2s
System.out.println("This one comes after 2 seconds from the println.");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2496 次 |
| 最近记录: |