0

我希望在 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.");
4

5 回答 5

5

只需使用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.");
}
于 2013-06-23T11:18:59.770 回答
3
try {
    Thread.sleep(2000); //2 secs
catch (InterruptedException e) {
}
于 2013-06-23T11:19:06.107 回答
2

你应该使用Thread#sleep

使当前执行的线程休眠

请注意,您应该try-catch在调用周围使用块,因为另一个线程可能会在它睡眠时Thread.sleep()中断。main()在这种情况下,没有必要捕获它,因为只有一个线程处于活动状态,main().

try {
    Thread.sleep(2000)
catch (InterruptedException e) {
    System.out.println("main() Thread was interrupted while sleeping.");
}
于 2013-06-23T11:28:13.390 回答
1
Thread.currentThread().sleep(2000); //2000 milliseconds = 2 seconds
于 2013-06-23T11:21:09.300 回答
1

如果你想让你的 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

于 2013-06-23T11:21:26.567 回答