我希望在 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.");
只需使用Thread#sleep:
System.out.println("First print.");
Thread.sleep(2000);//2000ms = 2s
System.out.println("This one comes after 2 seconds from the println.");
请注意,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.");
或者:
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.");
}
try {
Thread.sleep(2000); //2 secs
catch (InterruptedException e) {
}
你应该使用Thread#sleep:
使当前执行的线程休眠
请注意,您应该try-catch
在调用周围使用块,因为另一个线程可能会在它睡眠时Thread.sleep()
中断。main()
在这种情况下,没有必要捕获它,因为只有一个线程处于活动状态,main()
.
try {
Thread.sleep(2000)
catch (InterruptedException e) {
System.out.println("main() Thread was interrupted while sleeping.");
}
Thread.currentThread().sleep(2000); //2000 milliseconds = 2 seconds
如果你想让你的 java 代码休眠 2 秒,你可以在 Thread 中使用 sleep 函数:
Thread.sleep(millisec);
millisec 参数是您希望 f.ex 休眠多少毫秒:
1 sec = 1000 ms
2 sec = 2000 ms
and so on..
所以你的代码将是这样的:
System.out.println("First print.");
try {
Thread.sleep(2000); //2 secs
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("This one comes after 2 seconds from the println.");
(需要 try-catch 是因为有时如果 SecurityManager 不允许线程休眠但不要担心,这将永远不会发生。)
-Max